【问题标题】:Determining the unmatched portion of a string using a regex in Python在 Python 中使用正则表达式确定字符串的不匹配部分
【发布时间】:2010-02-03 20:48:26
【问题描述】:

假设我有一个字符串“a foobar”,我使用“^a\s*”来匹配“a”。

有没有办法让“foobar”轻松返回? (什么不匹配)

我想使用正则表达式来查找命令词,并使用正则表达式从字符串中删除命令词。

我知道如何使用类似的东西来做到这一点:

mystring[:regexobj.start()] + email[regexobj.end():]

但如果我有多个匹配项,这就会崩溃。

谢谢!

【问题讨论】:

  • 你能举例输入和输出吗?您将如何获得多个匹配项?你想要一组不匹配的部分吗?
  • string = "87 foo 87 bar" regex = "87\s*"

标签: python regex


【解决方案1】:

使用re.sub:

import re
s = "87 foo 87 bar"
r = re.compile(r"87\s*")
s = r.sub('', s)
print s

结果:

foo bar

【讨论】:

  • 正是我想要的。我知道有一个简单的方法。谢谢!
  • 您也可以将r = re.compile(); s = r.sub()合并到s = re.sub()中。
【解决方案2】:

来自http://docs.python.org/library/re.html#re.split

>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']

所以你的例子是

>>> re.split(r'(^a\s*)', "a foobar")
['', 'a ', 'foobar']

此时您可以将奇数项(您的匹配项)与偶数项(其余)分开。

>>> l = re.split(r'(^a\s*)', "a foobar")
>>> l[1::2] # matching strings
['a ']
>>> l[::2] # non-matching strings
['', 'foobar']

与 re.sub 相比,它的优势在于您可以知道何时、何地以及找到了多少匹配项。

【讨论】:

    【解决方案3】:
    >>> import re
    >>> re.sub("87\s*", "", "87 foo 87 bar")
    'foo bar'
    

    【讨论】:

      【解决方案4】:

      也许您可以使用 re.sub 代替拆分或分离,并在找到模式时替换一个空白的空字符串 ("")。比如……

      >>> import re
      >>> re.sub("^a\s*", "","a foobar")
      'foobar''
      >>> re.sub("a\s*", "","a foobar a foobar")
      'foobr foobr'
      >>> re.sub("87\s*", "","87 foo 87 bar")
      'foo bar'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-07-21
        • 2015-10-25
        • 2010-09-15
        • 1970-01-01
        • 2012-11-25
        • 1970-01-01
        相关资源
        最近更新 更多