0

I am capturing Bar via a named groupA and I would like to re-reference groupA capture to get a second group.

Sample string :

Foo:Bar Lorem ipsum Bar-564875XC4 dolor sit amet

Regex to capture Bar in groupA :

Foo:(?<groupA>[^\s]+)

Question : how to I complete this regex to re-capture <groupA> and get 564875XC4 in <groupB> ?

Philippe
  • 103
  • 1
  • 1
  • 8

2 Answers2

1

I would write your regex in C# as:

Foo:(?<groupA>\w+)(?: \w+)* \k<groupA>-(?<groupB>\w+)

More generally, you could also just use a numbered backreference:

Foo:(?<groupA>\w+)(?: \w+)* \1-(?<groupB>\w+)

Demo

Explanation:

  • Foo: match "Foo-"
  • (?<groupA>\w+) match and capture first word in <groupA>
  • (?: \w+)* then match space followed by a word, zero or more tkmes
  • match a single space
  • \k<groupA> match the first captured word (again)
  • - match "-"
  • (?<groupB>\w+) match and capture term of interest in <groupB>
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Answer with back-reference by name:

Foo:(?<groupA>\w+)(?: \w+)* \g<groupA>-(?<groupB>\w+)

Demo with named back-reference

Philippe
  • 103
  • 1
  • 1
  • 8