2

My input text file is like

A={5,6},B={2},C={3}
B={2,4}
A={5},B={1},C={3}
A={5},B={2},C={3,4,QWERT},D={TXT}

I would like to match all the lines where A=5,B=2 and C=3. The catch is, if variable is not mentioned, then that variable can take any value and hence that line also needs to be matched.

Above should match line 1,2 & 4.

I tried

.*?(?:(?=A)A\{.*?5).*?(?:(?=B)B\{.*?2).*?(?:(?=C)C\{.*?3)

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

But, it is not working

I shall be using this regex in a python 3.6 code.

4
  • 1
    Try ^(?!.*?A=[^5]).*?\bB=2\b.*. See live demo here regex101.com/r/0S0yre/1
    – revo
    Commented May 30, 2019 at 11:31
  • Probably, ^(?!.*\bA=(?!5\b)\d+).*\bB=2\b.* will work for you. It will make sure there is a number after A= that is not 5 if there is any A. Demo. BTW, (?=B)B = B, the lookahead is redundant here (as it requires B to be B). = are not special, no need to escape them here. Commented May 30, 2019 at 11:34
  • I can confirm that the above regex posted by @WiktorStribiżew works as intended.
    – Matthew
    Commented May 30, 2019 at 11:53
  • I think I over simplified the problem with only 2 variables. Hence I have changes my original question.
    – Karthik
    Commented May 30, 2019 at 12:49

1 Answer 1

1

If you want to solve it with a regex, you may use

^
 (?!.*\bA={(?![^{}]*\b5\b))
 (?!.*\bB={(?![^{}]*\b2\b))
 (?!.*\bC={(?![^{}]*\b3\b))
.*

See the regex demo

The point is to fail a match if there is a key that contains no given number value inside braces.

E.g. (?!.*\bA={(?![^{}]*\b5\b)) is a negative lookahead that fails the match if, immediately to the right of the current location, there is no - .* - any 0+ chars other than line break chars - \bA - a whole word A - ={ - ={ substring - (?![^{}]*\b5\b) - that is not followed with any 0+ chars other than { and } and then followed with 5 as a whole word.

Sample usage in Python 3.6:

import re
s = """A={5,6},B={2},C={3}
B={2,4}
A={5},B={1},C={3}
A={5},B={2},C={3,4,QWERT},D={TXT}"""
given = { 'A': '5', 'B': '2', 'C': '3'}

reg_pattern = ''
for key,val in given.items():
    reg_pattern += r"(?!.*\b{}={{(?![^{{}}]*\b{}\b))".format(key,val)

reg = re.compile(reg_pattern)

for line in s.splitlines():
    if reg.match(line):
        print(line)

Output:

A={5,6},B={2},C={3}
B={2,4}
A={5},B={2},C={3,4,QWERT},D={TXT}

Note the use of re.match, this method only searches for a match at the start of the string, so, no need adding ^ anchor (that matches string start).

1
  • 1
    This exactly meets my requirement. Thanks
    – Karthik
    Commented May 31, 2019 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.