3

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?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
124x
  • 43
  • 7

3 Answers3

3

This works:

>>> import re
>>> re.search( r'(xyz|abc)pqr', 'abcpqr' )
<_sre.SRE_Match object at 0x7fa3055bdeb0>
>>> re.search( r'(xyz|abc)pqr', 'abcpq' )
>>> 
lenik
  • 23,228
  • 4
  • 34
  • 43
3

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
Guy
  • 46,488
  • 10
  • 44
  • 88
2

Try this:

re.search(r'((xyz|abc).*pqr)|(pqr.*(xyz|abc))', line)
Anatoliy R
  • 1,749
  • 2
  • 14
  • 20