1

Suppose I have strings like the following :

OneTwo
ThreeFour
AnotherString
DVDPlayer
CDPlayer

I know how to tokenize the camel-case ones, except the "DVDPlayer" and "CDPlayer". I know I could tokenize them manually, but maybe you can show me a regex that can handle all the cases?

EDIT: the expected tokens are :

OneTwo -> One Two
...
CDPlayer -> CD Player
DVDPlayer -> DVD Player
2
  • 1
    And what tokens do you expect in this case? Commented Sep 7, 2009 at 12:05
  • 1
    One,Two; Three,Four; Another,String; DVD,Player; CD,Player Commented Sep 7, 2009 at 12:07

5 Answers 5

4

Look at my answer on the question, .NET - How can you split a “caps” delimited string into an array?.

The regex looks like this:

/([A-Z]+(?=$|[A-Z][a-z])|[A-Z]?[a-z]+)/g

It can be modified slightly to allow searching for camel-cased tokens, by replacing the $ with \b:

/([A-Z]+(?=\b|[A-Z][a-z])|[A-Z]?[a-z]+)/g
Sign up to request clarification or add additional context in comments.

1 Comment

The latter is almost equivalent to Gumbo's answer. The only difference is that this also accept words starting with lower-case. "camelCase" -> ["camel", "Case"]
4

Try this regular expression:

[A-Z](?:[a-z]+|[A-Z]*?(?=[A-Z][a-z]|\b))

Comments

1

The regex

([A-Z]+[a-z]*)([A-Z][a-z]*)

would do what you want assuming that all your strings are 2 words long and the second word is not like DVD.

I.e. it would work for your examples but maybe not for what you are actually trying to do.

Comments

1

Here's my attempt:

([A-Z][a-z]+)|([A-Z]+(?=[A-Z][a-z]+))

Comments

0

Try a non-greedy look ahead. A token would be one or more uppercase characters followed by zero or more lowercase characters. The token would terminate when the next two character are an upper case and lower case - matching this section is what the non-greedy matching can be used. This approach has limitation but it should work for the examples you provided.

1 Comment

+1 because you got there first -- though I guess an example might have pushed you up the "helpful" ranking :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.