Is there a way to use AND & OR operator together in re.search in python?
if re.search(r'xyz|abc', line) != None:
Here I have used OR operator, But my requirement is to get line containing ('xyz'
or 'abc'
) and 'pqr'
. How to do that?
Is there a way to use AND & OR operator together in re.search in python?
if re.search(r'xyz|abc', line) != None:
Here I have used OR operator, But my requirement is to get line containing ('xyz'
or 'abc'
) and 'pqr'
. How to do that?
This works:
>>> import re
>>> re.search( r'(xyz|abc)pqr', 'abcpqr' )
<_sre.SRE_Match object at 0x7fa3055bdeb0>
>>> re.search( r'(xyz|abc)pqr', 'abcpq' )
>>>
To ignore the order of the strings you can use
if re.search(r'(?=.*[pqr])(?=.*[xyz|abc])', line):
print('match')
line = 'xyzpqr' # match
line = 'pqrxyz' # match