I found a brilliant RegEx to extract the part of a camelCase or TitleCase expression.
(?<!^)(?=[A-Z])
It works as expected:
For example with Java:
String s = "loremIpsum"; words = s.split("(?<!^)(?=[A-Z])"); //words equals words = new String[]{"lorem","Ipsum"}
My problem is that it does not work in some cases:
To my mind, the result shoud be:
In other words, given n uppercase chars:
Any idea on how to improve this regex?
Another way to convert a camel case string into a capital case sentence is to use the split method to split a string at the start of each word, which is indicated by the capital letter. Then we can use join to join the words with a space character. We call split with the /(?
Camel case (sometimes stylized as camelCase or CamelCase, also known as camel caps or more formally as medial capitals) is the practice of writing phrases without spaces or punctuation. It indicates the separation of words with a single capitalized letter, and the first word starting with either case.
Camelcase is the practice of writing phrases without any spaces or punctuation between words. To indicate the separation between words, we isntead use a single capitalized letter for each word. Below are some examples: someLabelThatNeedsToBeCamelized. someMixedString.
The following regex works for all of the above examples:
public static void main(String[] args) { for (String w : "camelValue".split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")) { System.out.println(w); } }
It works by forcing the negative lookbehind to not only ignore matches at the start of the string, but to also ignore matches where a capital letter is preceded by another capital letter. This handles cases like "VALUE".
The first part of the regex on its own fails on "eclipseRCPExt" by failing to split between "RPC" and "Ext". This is the purpose of the second clause: (?<!^)(?=[A-Z][a-z]
. This clause allows a split before every capital letter that is followed by a lowercase letter, except at the start of the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With