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).*)
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:
^ (MULTILINE flag (m))^. All other patterns are lookahead patterns. And, it uses capture groups inside lookaheads to match the groups that were are looking for.^(?=.*(?: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.(...)? 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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With