This is a bit confusing, but let's see, I'll start with the second regular expression:
(a?)b\1c
When he tries to match bc , he first tries (a?) , But since there is no a in bc , () will write an empty string "" , so when we later refer to it in a string using \1 , \1 will be empty line that is always possible.
Now we pass to the second case:
(a)?b\1c
(a) will try to match a , but fail, but since the whole group (a)? is optional, the regular expression continues, now it tries to find b OK, then \1 , but (a)? do not match with anything, even with an empty string, so the match does not work.
So the difference between the two regular expressions is that in (a?) capture group captures an empty string, which can be referenced later, and successfully matches with \1 , but (a)? creates an optional capture group that does not match anything that references it later using \1 will always fail unless the group matches a .
source share