Skip to main content
 首页 » 编程设计

python之为什么这个python会重新匹配

2025年05月04日9jirigala

有人可以解释 python re 的这种奇怪行为吗?显然字符串“test”不包含“Bid”或“Ask”。为什么这样匹配?

import re 
pat=r'[Bid|Ask]' 
reg=re.compile(pat) 
if reg.search('test'): print "matched!" 

... 匹配!

请您参考如下方法:

[...]定义一个字符类,匹配其中列出的任何字符。你想要的是 par = r'(Bid|Ask)'。

但是,您应该根本不要为此使用正则表达式,而是执行以下操作:

if whatever in ('Bid', 'Ask'): 
    # it's one of these two 
else: 
    # it isn't 

如果您需要执行子字符串检查(感谢@agf):

if any(word in whatever for word in ('Bid', 'Ask')): 
    # one of the words is in the sting whatever