Thursday, June 27, 2019

regex - The meaning of \1* operator in Java regexes

\\1 is back reference corresponding in this case to the first capturing group which is (a) here.


So (a)\\1* is equivalent to (a)a* in this particular case.


Here is an example that shows the difference:


Pattern p1 = Pattern.compile("(a)\\1*");
Pattern p2 = Pattern.compile("(a)");
Matcher m1 = p1.matcher("aa");
Matcher m2 = p2.matcher("aa");
m1.find();
System.out.println(m1.group());
m2.find();
System.out.println(m2.group());

Output:


aa
a

As you can see when you have several a the first regular expression captures all the successive a while the second one captures only the first one.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...