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



任何人都可以提供指导,说明为什么以下正则表达式不起作用?

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

预期产出:-

AirPortFamily-1425.9

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

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

布兰登的回答看起来不错。

但是如果有一个条件,比如"为了使标签有效,它必须以冒号(:)结尾">
为了覆盖该条件,稍微修改一下 Brandon 的答案

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

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

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

关于1.1.1.1.1的可能性,我得到了:,所以只需将其从结果中删除即可

if re.findall(r'%s-[d+.d+]+:'%project,line):
print(line.strip(':'))
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 formats.py 
AirPortFamily-1425.9.1.1.1

这是我的正则表达式,我对正则表达式101的测试再次编辑

import re
project = 'AirPortFamily'
line = 'AirPortFamily-1425.9:AirPortfamily-14.5.9AirPortFamily-14.2.5.9:'
result = re.findall('%s[0-9.-]+:'%project,line) #this dose not cantain ':' [s[:-1] for s in re.findall('%s[0-9.-]+:'%project,line)]
if result:
for each in result:
print (each)

最新更新