To clarify, I want to match:
ab
aabb
aaabbb
...
This works in Perl:
if ($exp =~ /^(a(?1)?b)$/)
To understand this, look at the string as though it grows from the outside-in, not left-right:
ab
a(ab)b
aa(ab)bb
(?1)
is a reference to the outer set of parentheses. We need the ?
afterwards for the last case (going from outside in), nothing is left and ?
means 0 or 1 of the preceding expression (so it essentially acts as our base case).
I posted a similar question asking what is the equivalent (?1)
in Java? Today I found out that \\1
refers to the first capturing group. So, I assumed that this would work:
String pattern = "^(a(?:\\1)?b)$";
but it did not. Does anyone know why?
NB: I know there are other, better, ways to do this. This is strictly an educational question. As in I want to know why this particular way does not work and if there is a way to fix it.