为什么匹配项目标记的正则表达式不起作用?

2024-10-03 04:40:11 发布

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

有人能提供关于为什么下面的正则表达式不起作用的指导吗?你知道吗

project = 'AirPortFamily'
line = 'AirPortFamily-1425.9:'
if re.findall('%s-(\d+):'%project,line):
    print line

预期输出:-你知道吗

AirPortFamily-1425.9

Tags: reprojectifline指导printfindallairportfamily
3条回答

你的正则表达式缺少。在第一组数字之后。下面是一个工作示例:

project = 'AirPortFamily'
line = 'AirPortFamily-1425.9:'
matches = re.findall('%s-\d+\.\d+'%project,line)
if matches:
    print matches

布兰登的回答看起来不错。你知道吗

但如果有类似“标记要有效,必须以冒号(:)结尾”的条件,
为了掩盖这种情况,稍微修改一下布兰登的回答

project = 'AirPortFamily'
line = 'AirPortFamily-1425.9:'
matches = re.findall('%s-\d+\.+\d+\.*\d+:$'%project,line)
if matches:
    for elem in matches:
        print elem.split(':')[0]

这是它的工作原理

#Matching lines with colon(:) at the end
>>> import re
>>> project = 'AirPortFamily'
>>> line = 'AirPortFamily-1425.9:'
>>> matches = re.findall('%s-\d+\.+\d+\.*\d+:$'%project,line)
>>> if matches:
...     for elem in matches:
...             print elem.split(':')[0]
...
AirPortFamily-1425.9 #Look, the output is the way you want.

#Below snippet with same regex and different line content (without :) doesn't match it
>>> line = 'AirPortFamily-1425.9'
>>> matches = re.findall('%s-\d+\.+\d+\.*\d+:$'%project,line)
>>> if matches:
...     for elem in matches:
...             print elem.split(':')[0]
...
>>> #Here, no output means no match

您应该匹配前面有点的可选数字组:

if re.findall(r'(%s-\d+(?:\.\d+)*):'%project,line):

相关问题 更多 >