【问题标题】:regex to match MINUS with spaces正则表达式匹配 MINUS 和空格
【发布时间】:2018-03-07 01:32:29
【问题描述】:

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

r'[ - &]' 

所以,这里spaceMINUSspace 应该被视为一回事。

例如:

它应该匹配如下字符串:foo - barfoo&bar。它不应该与 foo-bar 这样的内容匹配。

请建议我该怎么做。

【问题讨论】:

  • 是否只需要匹配foo - barfoo&bar?或者任何两个词之间没有- 且没有空格的词。
  • 单词可以是任何单词。如果它由 spaceMINUSspace 分隔,它应该匹配。如果它被 & 分隔,它应该匹配。
  • 如果匹配必须包含单词,您介意编辑问题中的语言以反映这一点吗?

标签: python regex regex-group


【解决方案1】:

您可以尝试使用re.match,使用以下模式:

.*\w+(?:( - )|&)\w.*

这表示匹配两个单词,由-& 分隔。这是一个代码sn-p:

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

【讨论】:

  • 有理由使用.*\w+吗? \w+还不够吗?
  • @SeanBreckenridge 看起来re.match API 坚持模式匹配整个字符串(see here)。所以我在两端添加.* 以确保所有内容都匹配。
  • 我明白了。它似乎与from the beginning of the string 匹配,因此.*\w+(?:( - )|&)\w 也可以正常工作(尽管没有那么有用)。那么为什么不将re.search\w+(?:( - )|&)\w 一起使用呢? demo
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
  • 2011-02-11
  • 2018-02-16
  • 2010-10-08
相关资源
最近更新 更多