python中的重叠正则表达式

2024-04-25 19:55:07 发布

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

我一直在尝试用一个正则表达式来捕获python中的重叠模式,但没有成功。我需要能够从字符串中检测以下信息:

  'OC on pin 32 or 31'
  'OC on pin 32 or pin 31'
  'OC on pin 32 31'
  'OC on pin 32'

在上面的所有例子中,正则表达式应该产生最后一行的结果:(32,31)和(32)。你知道吗

我刚刚开始学习python和如何使用正则表达式,我想到了以下几点:

'^.*OC.*pin\s*([0-9][0-9])(?:\s*or\s*)?(?:\s*pin\s*)?([0-9][0-9])?'

它只适用于上面示例中的第一行,据我所知,当第二个“pin”在输入字符串中时,它似乎是重叠的。你知道吗

pattern = '^.*OC.*pin\s*([0-9][0-9])(?:\s*or\s*)?(?:\s*pin\s*)?([0-9][0-9])?'
str = 'OC on pin 32'
re.findall(pattern, str)
[('32', '')]

对于另一种情况:

str = 'OC on pin 32 or pin 31'
re.findall(pattern, str)
[('31', '')]

有没有一种方法可以捕获上面所有的情况,而不必在使用regex之前更改字符串bre?你知道吗


Tags: or方法字符串re信息示例onpin
2条回答

正如这里已经回答的(没有解释),您过度指定了您的搜索模式。你知道吗

如果您想提取一组数字,那么模式\d+就可以做到这一点。你知道吗

虽然可以对字符串以OC on pin开头进行语法验证,但可以将其插入正则表达式中,但是使用类似

if str.startswith('OC on pin'):
    ...

你的问题来自于.*贪婪地匹配这个事实。你知道吗

pattern = '^.*OC.*pin\s*([0-9][0-9])(?:\s*or\s*)?(?:\s*pin\s*)?([0-9][0-9])?'
#                ^ will consume way more than you want

一个解决方案是使用.*?来匹配非贪婪。我可以想出有效的解决办法。你知道吗

pattern = r'OC.*?pin\s*(\d+)\s*(?:or)?\s*(?:pin)?\s*(\d+)?'
#               ^ this indicates that .*? should not attempt to consume 'pin'

string = """
    OC on pin 32 or 31'
    OC on pin 32 or pin 31'
    OC on pin 32 31'
    OC on pin 32'
"""

match = re.findall(pattern, string)
# match: [('32', '31'), ('32', '31'), ('32', '31'), ('32', '')]

相关问题 更多 >