1

So I have this king of string:

some_string-1.4.2.4-RELEASE.some_extension

And I want to parse the version number (in my example: 1.4.2.4) But the number between the dots will not always be 1 digit, it could be something like: 1.40.2.4 or 11.4.2.4.

This is what i have tried:

(\d+\.)?\d+\.\d+

And this does not parse all the numbers.

EDIT

I tried to use the answer from the duplicate link: \d+(\.\d+)+

And according to regex101 I get this result:

Full match  17-24   1.4.2.4
Group 1.    22-24   .4

But in my code I got only .4:

file_name = 'some_string-1.4.2.4-RELEASE.some_extension'

match = re.findall('\d+(\.\d+)+', file_name)
if len(match) == 0:
    print('Failed to match version number')
else:
    print(match[0])
    return match[0]
0

3 Answers 3

0

You might want to consider the following pattern :

file_name = 'some_string-1.4.2.4-RELEASE.some_extension'

pattern = r'\-([0-9.-]*)\-'
match = re.findall(pattern, file_name)
if len(match) == 0:
    print('Failed to match version number')
else:
    print(match[0])

output:

1.4.2.4

Sign up to request clarification or add additional context in comments.

Comments

0

Your pattern is almost right.

Use

(\d+(?:\.\d+)+)

This changes the first group to be the entire version number, and ignore the internal repeating group.

str = "some_string-1.4.2.4-RELEASE.some_extension"
regex = r'''(\d+(?:\.\d+)*)'''
print(re.findall(regex, str))  # prints ['1.4.2.4']

Comments

0

The pattern \d+(\.\d+)+ contains a repeating capturing group and will contain the value of the last iteration which is .4 and will be returned by findall.

If you would make it a non capturing group it will match the whole value but also values like 1.1 and 9.9.9.99.9.9

\d+(?:\.\d+)+

If the digits must consists of 3 dots and between hyphens, you might use a capturing group:

-(\d+(?:\.\d+){3})-

Regex demo

Or use lookarounds to get a match without using a group:

(?<=-)\d+(?:\.\d+){3}(?=-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.