I have a string I need to split based on capital letters,my code below
let s = 'OzievRQ7O37SB5qG3eLB';
var res = s.split(/(?=[A-Z])/)
console.log(res);
I have a string I need to split based on capital letters,my code below
let s = 'OzievRQ7O37SB5qG3eLB';
var res = s.split(/(?=[A-Z])/)
console.log(res);
But there is a twist,if the capital letters are contiguous I need the regex to "eat" until this sequence ends.In the example above it returns
..R,Q7,O37,S,B5q,G3e,L,B
And the result should be
RQ7,O37,SB5q,G3e,LB
Thoughts?Thanks.
Share Improve this question asked Mar 15, 2017 at 8:50 MihaiMihai 26.8k8 gold badges69 silver badges86 bronze badges 3- 1 'OzievRQ7O37SB5qG3eLB'.match(/[A-Z]+[^A-Z]+/g) ? – Andrey Commented Mar 15, 2017 at 8:57
- @Andrey Post it as an answer – Mihai Commented Mar 15, 2017 at 9:00
- Wiktor got it :) His regex is actually better – Andrey Commented Mar 15, 2017 at 9:03
1 Answer
Reset to default 5You need to match these chunks with /[A-Z]+[^A-Z]*|[^A-Z]+/g
instead of splitting with a zero-width assertion pattern, because the latter (in your case, it is a positive lookahead only regex) will have to check each position inside the string and it is impossible to tell the regex to skip a position once the lookaround pattern is found.
s = 'and some text hereOzievRQ7O37SB5qG3eLB';
console.log(s.match(/[A-Z]+[^A-Z]*|[^A-Z]+/g));
See the online regex demo at regex101..
Details:
[A-Z]+
- one or more uppercase ASCII letters[^A-Z]*
- zero or more (to allow matching uppercase only chunks) chars other than uppercase ASCII letters|
- or[^A-Z]+
- one or more chars other than uppercase ASCII letters (to allow matching non-uppercase ASCII letters at the start of the string.
The g
global modifier will let String#match()
return all found non-overlapping matches.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745037221a4607594.html
评论列表(0条)