Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex skip missing groups

Tags:

regex

This captures groups a, b, c in any order: (?<=some_text_here)(?=.*(?P<a>A).*)(?=.*(?P<b>B).*)(?=.*(?P<c>C).*)

some_text_here A B C
some_text_here A C B
some_text_here B C A
some_text_here C A B

I need the option to skip missing fields without dropping the entire line:

some_text_here A B C
some_text_here A C B
some_text_here B A
some_text_here C

This just creates chaos: (?<=some_text_here)|(?=.*(?P<a>A).*)|(?=.*(?P<b>B).*)|(?=.*(?P<c>C).*)

like image 660
John Paul Avatar asked Oct 25 '25 06:10

John Paul


2 Answers

Updated regex pattern, demo, and notes

REGEX PATTERN (PRCE2 Flavor with GLOBAL and MULTILINE flags):

^(?=.*(?:A|B|C))(?=.*(?P<a>A))?(?=.*(?P<b>B))?(?=.*(?P<c>C))?

UPDATED: Regex demo: https://regex101.com/r/1oYDOF/10 (4 matches, 1-3 capture groups per match, 683 steps)

NOTES:

  • The pattern is anchored at the start of line ^ (MULTILINE flag (m))
  • Except for the anchor ^. All other patterns are lookahead patterns. And, it uses capture groups inside lookaheads to match the groups that were are looking for.
  • The groups can be in any order.
  • The same group matches only once per line.
  • The groups that we are matching are known, A, B and C.
  • Skips the line if there are not group to be matched, i.e. no empty string matches.
  • ^(?=.*(?:A|B|C)) This lookahead, (?=...), must match for the line. It matches, but does not consume any characters. It matches if on the line, after 0 or more characters, .*, there is one of the groups A OR B OR C, ((A|B|C)). This makes sure that we will not match a line without any of the groups.
  • We use the following three optional (...)? lookahead patterns (?=...) to check for (match) and capture groups A, B and C into capture groups (?P<name>...) named a, b and c respectively: (?=.*(?P<a>A))? (?=.*(?P<b>B))? (?=.*(?P<c>C))? Each of the lookahead pattern will try to match, but will not consume any part of the string, leaving it available for the other patterns to try to match.
like image 136
rich neadle Avatar answered Oct 27 '25 01:10

rich neadle


It can be done in PCRE like this :

^(?:.*?(?:(?(1)(?!))(?<a>A)|(?(2)(?!))(?<b>B)|(?(3)(?!))(?<c>C))){1,3}

https://regex101.com/r/NGuFRJ/1

and in Python like this :

^(?:.*?(?:(?(1)(?!))(?P<a>A)|(?(2)(?!))(?P<b>B)|(?(3)(?!))(?P<c>C))){1,3}

https://regex101.com/r/S7E6aW/1

The difference is the Python Rx is using the (?P<name>) grouping convention.

These work by finding at least one, but only one each of A,B, or C in the range of {1,3}

This is out of order matching without use of assertions.

like image 28
sln Avatar answered Oct 27 '25 03:10

sln



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!