Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  178] [ 2]  / answers: 1 / hits: 13530  / 11 Years ago, wed, january 29, 2014, 12:00:00
$ node
> ababaabab.split(/a{2}/)
[ 'abab', 'bab' ]
> ababaabab.split(/(a){2}/)
[ 'abab', 'a', 'bab' ]
>


So, this doesn't make sense to me. Can someone explain it? I don't get why the 'a' shows up.



Note: I am trying to match for doubled line endings (possibly on windows files) so I am splitting on /(r?n){2}/. However I get extraneous '15n' entries in my array (note 15 == r).



Why are these showing up?



Note: also affects JS engine in browsers so this is specific to JS not node.


More From » regex

 Answers
12

In your second result, a is appearing because you've wrapped it in a capture group () (parentheses).



If you want to not include it but you still require a conditional group, use a non-capturing group: (?:a). The questionmark-colon can be used inside any capture group and it will be omitted from the resulting list of captures.



Here's a simple example of this in action: http://regex101.com/r/yM1vM4


[#48262] Tuesday, January 28, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trinityr

Total Points: 49
Total Questions: 107
Total Answers: 96

Location: Mayotte
Member since Fri, Oct 1, 2021
3 Years ago
;