showkey
showkey

Reputation: 300

How to express logical or in regular expression in python?

How to express logical or in regular expression in python? Why re.search("o"|"a","hallo") and re.search(("o"|"a"),"hallo") is wrong?

>>> if(re.search("a","hallo")):print("ok")
...
ok
>>> if(re.search("o","hallo")):print("ok")
...
ok
>>> if(re.search("o"|"a","hallo")):print("ok")
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'str' and 'str'
>>> if(re.search(("o"|"a"),"hallo")):print("ok")
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'str' and 'str'

Upvotes: 0

Views: 5153

Answers (1)

sshashank124
sshashank124

Reputation: 32189

You should instead do it as:

re.search(r"(o|a)","hallo")

The "" should encompass the whole pattern.

You could also do:

re.search(r"[oa]","hallo")

Upvotes: 3

Related Questions