Regex divide by uppercase and first digit

I need to split the string "thisIs12MyString" into an array similar to [ "this", "Is", "12", "My", "String" ]

It is still up to "thisIs12MyString".split(/(?=[A-Z0-9])/) , but it is split into each digit and gives an array [ "this", "Is", "1", "2", "My", "String" ]

So, in words, I need to break the string into an uppercase letter and numbers that do not have another digit in front of it.

+4
source share
5 answers

Are you looking for this?

 "thisIs12MyString".match(/[AZ]?[az]+|[0-9]+/g) 

returns

 ["this", "Is", "12", "My", "String"] 
+9
source

As I said in my comment, my approach was to insert a special character before each sequence of digits first as a marker:

 "thisIs12MyString".replace(/\d+/g, '~$&').split(/(?=[AZ])|~/) 

where ~ can be any other character, preferably non-printable (for example, a control character), since it is unlikely to appear "naturally" in the string.

In this case, you can even insert a marker in front of each uppercase letter, and also lower your eyes, which will greatly simplify the separation:

 "thisIs12MyString".replace(/\d+|[AZ]/g, '~$&').split('~') 

It may or may not work better.

+3
source

In my rhino console

 js> "thisIs12MyString".replace(/([AZ]|\d+)/g, function(x){return " "+x;}).split(/ /); this,Is,12,My,String 

other,

 js> "thisIs12MyString".split(/(?:([AZ]+[az]+))/g).filter(function(a){return a;}); this,Is,12,My,String 
+1
source

I can’t think of any ways to achieve this with RegEx.

I think you will need to do this in code.

Please check the url, same question in another language (ruby) β†’

Code below: http://code.activestate.com/recipes/440698-split-string-on-capitalizeduppercase-char/

0
source

You can fix the lack of JS for lookbehinds working with an array section using the current regular expression.
Fast pseudo code:

 var result = []; var digitsFlag = false; "thisIs12MyString".split(/(?=[A-Z0-9])/).forEach(function(word) { if (isSingleDigit(word)) { if (!digitsFlag) { result.push(word); } else { result[result.length - 1] += word; } digitsFlag = true; } else { result.push(word); digitsFlag = false; } }); 
0
source

Source: https://habr.com/ru/post/1398466/


All Articles