任何人都可以提供有关以下正则表达式为何不起作用的指导吗?
project = 'AirPortFamily'
line = 'AirPortFamily-1425.9:'
if re.findall('%s-(\d+):'%project,line):
print line
预期的输出:-
AirPortFamily-1425.9
答案 0 :(得分:1)
您应该匹配可选的数字组,并在其前加上一个点:
tree /a /f > tree.txt
答案 1 :(得分:1)
布兰登的答案看起来不错。
但是如果出现类似“要使标签有效,它必须以冒号(:)结尾”的条件,
为了解决该问题,请对布兰登的答案进行一些修改
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
答案 2 :(得分:0)
您的正则表达式缺少。在第一组数字之后。这是一个工作示例:
project = 'AirPortFamily'
line = 'AirPortFamily-1425.9:'
matches = re.findall('%s-\d+\.\d+'%project,line)
if matches:
print matches
答案 3 :(得分:0)
这是我的正则表达式,my test on regex101 edit again
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)
答案 4 :(得分:0)
关于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