简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM