Why the regex to match a project tag is not working?

Viewed 70

Can anyone provide guidance on why the following regex is not working?

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

EXPECTED OUTPUT:-

AirPortFamily-1425.9
5 Answers

You should match the optional groups of digits preceded by a dot:

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

Answer by Brandon looks good.

But in case there is a condition like "For a tag to be valid, it must end with a colon(:)"
In order to cover that condition, modifying Brandon's answer a little

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]

Here is its working

#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

Your regex is missing the . after the first set of numbers. Here's a working example:

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

This is my regex,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)

On the possibilities with 1.1.1.1.1 I'm getting the : so just stripping it from the results

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
Related