我必须定义一个正则表达式:
r'[ - &]'
所以,这里spaceMINUSspace
应该被视为一回事。
例如:
它应该匹配像这样的字符串:foo - bar
和foo&bar
。它不应该匹配这样的东西foo-bar
。
请建议我如何做到这一点。
您可以尝试使用re.match
, 与以下模式:
.*\w+(?:( - )|&)\w.*
这表示匹配两个单词,以-
或分隔&
。这是一个代码片段:
line = "foo - bar"
match = re.match( r'.*\w+(?:( - )|&)\w.*', line, re.M|re.I)
if match:
print "Found this match: ", match.group()
或者,正如@Sean 指出的那样,我们可以使用re.search
:
line = "foo - bar"
pattern = re.compile(r'\w+(?:( - )|&)\w')
if pattern.search(line):
print "Found this match: ", line
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句