python re:匹配除了双线换行之外的所有内容

时间:2015-02-17 14:04:39

标签: python regex negative-lookahead

这里有很多这样的问题,但是我找不到一个我需要的问题。

我需要一个正则表达式,除了双重换行符之外的任何东西。更具体地说,这是一个例子:

数据:

# 1 main header

__1.1__ company consents to transfer of the following end user license - including...

__1.1.1__ A subparagraph

__1.2__ company also consents to other stuff...
Lorem ipsum dolor sit amet, consectetur aquisquam veniam!
{: #lorem_section }

我想要做的是查找以__[\d+\.?]+__开头且以\{: #\w+ \}结尾的每个部分。

为了做到这一点,我需要正则表达式的中间部分来匹配除双线换行之外的任何东西。我最初是这样做的:__([\d+\.?]+)__.*\{: (#\w+) \},但由于它也会捕获双重换行符,因此我会收到从__1.1__{: #lorem_section }的所有内容,其中我实际上需要从__1.2__到{{{: #lorem_section }的所有内容1}}。

我读到了关于消极前瞻,这可能是我需要的,但我似乎无法让它正常工作。我尝试了以下2个正则表达式,但都没有产生任何结果

__([\d+\.?]+)__.*(?!\n\n)\{: (#\w+) \}

__([\d+\.?]+)__(?!\n\n)*\{: (#\w+) \}

2 个答案:

答案 0 :(得分:3)

你需要使用否定的前瞻。

r'(?s)__[\d.]+__(?:(?!\n\n).)*?\{: #\w+ \}'

(?s)启用DOTALL模式,这使得正则表达式中出现的点也与换行符匹配。 (?:(?!\n\n).)*?会对任何字符进行非贪婪的匹配,但不会\n\n,不能进行零次或多次。

DEMO

>>> s = '''# 1 main header

__1.1__ company consents to transfer of the following end user license - including...

__1.1.1__ A subparagraph

__1.2__ company also consents to other stuff...
Lorem ipsum dolor sit amet, consectetur aquisquam veniam!
{: #lorem_section }'''
>>> m = re.findall(r'(?s)__[\d.]+__(?:(?!\n\n).)*?\{: #\w+ \}', s)
>>> for i in m:
        print(i)


__1.2__ company also consents to other stuff...
Lorem ipsum dolor sit amet, consectetur aquisquam veniam!
{: #lorem_section }

OR

你也可以这样做。

>>> for i in s.split('\n\n'):
        if re.match(r'(?s)__[\d.]+__.*\{: #\w+ \}$', i):
            print(i)


__1.2__ company also consents to other stuff...
Lorem ipsum dolor sit amet, consectetur aquisquam veniam!
{: #lorem_section }

答案 1 :(得分:0)

与不捕获双线结尾的问题分开,请注意+和?角色组[\d+\.?]中的字符被视为普通字符而不是量词。也就是说,它们将匹配自己,以便您的表达式__[\d+\.?]+__将匹配以下表达式:

__?__
__+__
__?+???__

依此类推,如https://regex101.com/r/sQ8iN1/2

所示

如果您想要应用量词并且想要重复组,则需要使用括号而不是括号,如https://regex101.com/r/sQ8iN1/3