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
你的正则表达式缺少。在第一组数字之后。下面是一个工作示例:
布兰登的回答看起来不错。你知道吗
但如果有类似“标记要有效,必须以冒号(:)结尾”的条件,
为了掩盖这种情况,稍微修改一下布兰登的回答
这是它的工作原理
您应该匹配前面有点的可选数字组:
相关问题 更多 >
编程相关推荐