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> ?
CodePudding user response:
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 tkmesmatch a single space\k<groupA>match the first captured word (again)-match "-"(?<groupB>\w )match and capture term of interest in<groupB>
CodePudding user response:
Answer with back-reference by name:
Foo:(?<groupA>\w )(?: \w )* \g<groupA>-(?<groupB>\w )
