We’re learning about the difference between regular languages and regex, and the teacher explained that the language
a^n b^n
is not regular, but she said that most regex flavors can match
a^n A^n
and she gave this problem for our extra credit homework problem. We’ve been struggling for a couple of days now, and could really use some guidance.
The teacher gave a HUGE hint by limiting the alphabet to
{a, A}. The key to solving this problem is realizing that in case-insensitive mode,amatchesAand vice versa. The other component of the problem is matching on backreference.This pattern will match
a{n}A{n}for somen(as seen on rubular.com):How it works
The pattern works as follows:
^(?=(a*)A*$)– Anchored at the beginning of the string, we use positive lookahead to see if we can match(a*)A*until the end of the string\1captures the sequence ofa{n}a{n}A{n}, since it’s not evena*A*\1(?i)\1$, that is, thea{n}captured by\1, then in case-insensitive mode(?i), we matcha{n}again until the end of the stringa*A*\1isa{n}\1(?i)\1can only bea{n}A{n}Related questions
References
See also