【问题标题】:How to catch a pattern that's not in the non-capturing group? - Python如何捕获不在非捕获组中的模式? - Python
【发布时间】:2018-03-28 01:57:51
【问题描述】:

给定字符串:

I'll be going home I've the 'v ' isn't want I want to split but I want to catch tokens like 'v and 'w ' .

目标是捕捉:

'v 
'v
'w

但请避免使用 've'll't

我试图用(?i)\'(?:ve|ll|t)\b 来捕捉've'll't,例如

>>> import re
>>> x = "I'll be going home I've the 'v ' isn't want I want to split but I want to catch tokens like 'v and 'w ' ."
>>> pattern = r"(?i)\'(?:ve|ll|t)\b"
>>> re.findall(pattern, x)
["'ll", "'ve", "'t"]

但是我也尝试过像这样(?i)\'[^(?:ve|ll|t)]\b 否定(?i)\'(?:ve|ll|t)\b 中的非捕获组,但它没有捕获'v'w,这是预期的目标。

如何捕获单引号后面但不是来自预定义子字符串列表的子字符串,即'll've't


这个我也试过了,还是不行:

pattern = "(?i)\'(?:[^ve|ll|t|\s])\b"

[^...] 只识别单个字符而不识别子字符串。

【问题讨论】:

    标签: python regex quotation-marks capturing-group


    【解决方案1】:

    也许这个one 会起作用?

    \'(?!ve|ll|t|\s)\w+
    

    您可以使用前瞻断言来过滤您不想要的内容。

    更新

    在其他一些语言中,模式前瞻断言必须是固定长度。

    这意味着(?!ve|t) 无效,因为vet 有两个不同的长度。

    【讨论】:

      【解决方案2】:

      非捕获组的负前瞻是(?!...),所以它类似于(?i)\'(?!ve|ll|t)\w\b

      >>> pattern = r"(?i)\'(?!ve|ll|t)\w\b"
      >>> x = "I'll be going home I've the 'v ' isn't want I want to split but I want to catch tokens like 'v and 'w ' ."
      >>> re.findall(pattern, x)
      ["'v", "'v", "'w"]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-11
        • 1970-01-01
        • 1970-01-01
        • 2014-08-01
        • 2019-01-12
        相关资源
        最近更新 更多