如何在python中表达逻辑或正则表达式?

时间:2014-04-03 12:49:22

标签: python regex

如何在python中表达逻辑或正则表达式? 为什么re.search("o"|"a","hallo")re.search(("o"|"a"),"hallo")错了?

>>> 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'

1 个答案:

答案 0 :(得分:3)

你应该这样做:

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

""应涵盖整个模式。

你也可以这样做:

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