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).
^(?!.*?A=[^5]).*?\bB=2\b.*
. See live demo here regex101.com/r/0S0yre/1^(?!.*\bA=(?!5\b)\d+).*\bB=2\b.*
will work for you. It will make sure there is a number afterA=
that is not5
if there is anyA
. Demo. BTW,(?=B)B
=B
, the lookahead is redundant here (as it requiresB
to beB
).=
are not special, no need to escape them here.