JavaScript, what does the regular expression / (a) \ 1 + /?

https://regex101.com/r/dS8mZ0/1

As I understand it, this expression is similar to / (a) {2,} /, but the description of such (/ (a) \ 1 + /) syntax cannot be found.

  • 2
    \ 1 is a link to the first saved group. In this case (a) . If my memory serves me, such groups in JS can be saved up to 9. PS: If you are interested in learning regular expressions, I highly recommend the 3rd edition of the book " Regular Expressions " (2008 Jeffrey Friedl) - HA3IK

2 answers 2

(a) - a group of a
\1 - the requirement to repeat the match with the first group
\1+ - the requirement to repeat the match with the first group one or more times.

Yes, in this case, the expression is equivalent to: (a){2,}

But in this - no longer: ([ab])\1+ - it is equivalent to essentially a{2,}|b{2,} , although getting the same first group in the last version will not work.

For more complex constructions, the equivalent expression will be much more difficult or even impossible to construct.

    A small visualization may be useful in addition to the first answer:

     (a)\1+ 

    Regular expression visualization

    Debuggex demo