简体   繁体   中英

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'

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM