3

Given a regex like

(a|b){2}\1

What will \1 refer to? The first capture, the last capture, or what?

Regex.IsMatch("aba", @"^(?:(a|b){2}\1)$") == False
Regex.IsMatch("abb", @"^(?:(a|b){2}\1)$") == True

Leads me to suspect it matches the last capture. I'm I correct in this assumption?

mpen
  • 272,448
  • 266
  • 850
  • 1,236

1 Answers1

3

You guessed right. Java does this, too. Most (if not all) regex engines store the last capture for repeated groups.

See http://www.regular-expressions.info/brackets.html#repeat for a general description.

See http://msdn.microsoft.com/en-us/library/aa719621%28v=VS.71%29.aspx for a confirmation regarding .Net:

"[...] when a group makes multiple captures, a backreference refers to the most recent capture."

Christian Semrau
  • 8,913
  • 2
  • 32
  • 39