Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to split camel case

I have a regular expression in JavaScript to split my camel case string at the upper-case letters using the following code (which I subsequently got from here):

"MyCamelCaseString"     .replace(/([A-Z])/g, ' $1')     .replace(/^./, function(str){ return str.toUpperCase(); }) 

Thus that returns:

"My Camel Case String" 

Which is good. However, I want to step this up a notch. Could someone help me with a regex which will split if, and only if, the former character is lower-case and the latter is upper-case.

Thus, the above example will be the result I expect, but if I do:

"ExampleID" 

Then I get returned:

"Example ID" 

Instead of

"Example I D" 

Since it's splitting at each upper-case and ignoring anything before it.

Hope that makes sense! And thanks :).

like image 702
keldar Avatar asked Aug 22 '13 11:08

keldar


People also ask

How do you split a camel case?

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.

How do you break a camel case in python?

First, use an empty list 'words' and append the first letter of 'str' to it. Now using a for loop, check if the current letter is in lower case or not, if yes append it to the current string, otherwise, if uppercase, begin a new individual string.

What is camel case with example?

Meaning of camel case in English. the use of a capital letter to begin the second word in a compound name or phrase, when it is not separated from the first word by a space: Examples of camel case include "iPod" and "GaGa".


1 Answers

My guess is replacing /([A-Z])/ with /([a-z])([A-Z])/ and ' $1' with '$1 $2'

"MyCamelCaseString"     .replace(/([a-z])([A-Z])/g, '$1 $2'); 

/([a-z0-9])([A-Z])/ for numbers counting as lowercase characters

console.log("MyCamelCaseStringID".replace(/([a-z0-9])([A-Z])/g, '$1 $2'))
like image 157
Michiel Dral Avatar answered Sep 24 '22 11:09

Michiel Dral