【问题标题】:findall not retruning all the results in Python 3.7findall 没有返回 Python 3.7 中的所有结果
【发布时间】:2018-07-16 07:22:52
【问题描述】:

我正在尝试使用字符串string1string3 之后的数据创建元组列表。但没有得到预期的结果。

s = 'string1:1234string2string3:a1b2c3string1:2345string3:b5c6d7'
re.findall('string1:(\d+)[\s,\S]+string3:([\s\S]+',s)

实际结果:

[('1234', 'b5c6d7)']

预期结果:

[('1234', 'a1b2c3'), ('2345', 'b5c6d7')]

【问题讨论】:

标签: python regex python-3.x


【解决方案1】:

您当前的正则表达式使用[\s,\S]+,它是贪婪的并且匹配所有字符直到行尾。

你可以让它变得不贪婪,并使用积极的前瞻 (?=string|$) 来断言最后一个匹配是 string 或行尾 $

string1:(\d+).*?string3:(.*?)(?=string|$)

import re 
s = 'string1:1234string2string3:a1b2c3string1:2345string3:b5c6d7'
print(re.findall('string1:(\d+).*?string3:(.*?)(?=string|$)',s))

Demo

【讨论】:

    【解决方案2】:

    问题在于[\s,\S]+ 是贪婪的,因此会消耗第一个字符串 1 和最后一个字符串 3 之间的所有内容。

    您可以通过使用积极的前瞻并像这样使正则表达式不贪婪来解决这个问题:

    string1:(\d+)[^\d][\s,\S]+?string3:([\s\S]+?(?=string|$))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 2021-11-21
      • 1970-01-01
      相关资源
      最近更新 更多