Python正则表达式+元字符不贪婪

2024-05-15 08:15:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这根绳子。你知道吗

string = """Horseradish CULTURE: Well-drained, friable soil with a pH range of 6.2-6.8 will yield the best results. When roots are received, work the soil about a foot deep and incorporate compost, manure, or fertilizer. Make a 5-6" deep furrow and plant root cuttings 12" apart, slanted 2-3" deep with the flat-cut end up..."""

这个密码呢

seed_spacing = re.search(r'(?:sow|transplant|plant)(?:(?!rows).)+(\d+)(\'|") apart', string, re.I)
seed_spacing.group()
>>>Make a 5-6" deep furrow and plant root cuttings 12" apart
seed_spacing.group(1)
>>>2

我想看12,但我得到了2。我需要这是一个灵活的情况下,它是一位数字。我以为+很贪婪。我错过了什么?你知道吗


Tags: andtherestringmakewithrootseed
2条回答

这部分

(?:(?!rows).)+

你的正则表达式的一部分是贪婪的,它匹配到1,所以像这样使它非贪婪

(?:(?!rows).)+?

你会得到

seed_spacing.group(1)

作为

12

+是贪婪的-但它不仅仅是\d+中的贪婪,它也是(?:(?!rows).)+中的贪婪。后者正在吃1。也许你更喜欢(?:(?!rows)\D)+(也就是说,吃那些不是数字的字符)。你知道吗

相关问题 更多 >