Balaji
Balaji

Reputation: 53

Consuming a Lookaround or Ignoring a Non-Capture in a Regex match

Consider the following string: ABC. I would like to capture the following groups using a regular expression:

Group1: AC
Group2: B

Both the groups have to be captured using a single regular expression. I do not have control over the code, so sub-matches or capture groups will not help.

I've tried both non-capturing groups and look arounds.

With a Non-Capturing group, the match is still a part of the final result.

(?<Group1>a(?:(?<Group2>b))c)

Group1: ABC # Not right as B is part of the match. Group2: B

With a lookaround, Group2 is not consumed and the regex following the look ahead should match the contents of Group2 again which includes it as part of Group1.

(?<Group1>a(?=(?<Group2>b))bc)

Group1: ABC # Not right as B is part of the match. Group2: B

How can I ignore "B" as part of the Group1 match?

Any help on getting around this is greatly appreciated.

Thanks, Balaji

Upvotes: 2

Views: 269

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

You can't. Regex engines can't paste together nonlinear submatches into a single match. Any match must be a succession of characters from the original text.

Upvotes: 1

Related Questions