将 MINUS 与空格匹配的正则表达式

regex to match MINUS with spaces

我必须定义一个正则表达式:

r'[ - &]' 

所以,这里spaceMINUSspace应该是一回事

例如:

它应该匹配如下字符串:foo - barfoo&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