Bhaskar vedula Bhaskar vedula - 1 month ago 6
Python Question

Python re.search regex using or condition

Hi Friends I'm trying to include "or |" condition in search pattern using re.search. Can someone help me how to achieve or condition as I'm not getting match.
Below code works

>>> pattern = re.escape('apple.fruit[0]')
>>> sig = 'apple.fruit[0]'
>>> if re.search(pattern, sig):
... print("matched")
...
matched
>>> pattern = re.escape('apple.fruit[0] or vegi[0]')
>>> if re.search(pattern, sig):
... print("matched")
...
>>>


I want to match above string "apple." followed by fruit[0] or vegi[0]

Answer

Regex or should be achieved through | operator and we don't inculde this inside re.escape. If you do so, then it would loose it's special meaning.

pattern = re.escape('apple.fruit[0]')+ '|' + re.escape('vegi[0]')

or

pattern = r'apple\.fruit\[0\]|vegi\[0\]'