mpen
mpen

Reputation: 282825

Why does this regex fail to match?

Regex.IsMatch("ab", @"^(?:(a)|\1b)$") == False

So it attempts to match a, succeeds, then tries to match $, fails, so it backtracks and tries the other disjunct, which starts with \1. I assume when it hit the "a" \1 took the value "a", but now because it had to backtrack it forgot that value? Is that how it works? And \1 will just fail to match anything after that point?

Upvotes: 1

Views: 138

Answers (1)

cdhowie
cdhowie

Reputation: 168988

Backreferences in regular expressions always match only what is currently being matched against. This is a consistency issue -- sections of the string that are not matched should not pollute the state of the matching engine, since that would result in a false positive.

So yes, you are correct: the \1 backreference will never match anything (not even the empty string) because the capture group that it corresponds to will also never match, since it is on the other side of an alternation operator.

Upvotes: 4

Related Questions