1

Using a rest api I get the following forms of strings back:

/primerjs-0.0.3-3.tgz
/primerjs-0.0.3.tgz
/0.0.3-16

I want to grab just the 0.0.3 part from the above strings. I came up with the following regex expression:

(\d+\.)+\d*(?!tgz)

and I have tested it on an online regex tester and it seems to grab what I want it to. However the following code only prints ['0.']

text = '/primerjs-0.0.9.tgz'
m = re.findall(r"(\d+\.)+\d*(?!tgz)", text)
print m

what am I doing wrong?

2 Answers 2

4

Use a non-capturing group:

(?:\d+\.)+\d*(?!tgz)

See the regex demo

Or, use an alternative pattern:

[/-](\d+\.\d+\.\d+)

See another demo

Both will work well with re.findall with your examples. The first one has no capturing groups, so re.findall will output match values, and the second will output only captured values (Group 1 contents) since re.findall returns capture group contents if capturing groups are defined inside the pattern.

Python demo:

import re
rx = r'[/-](\d+\.\d+\.\d+)'
print(re.findall(rx, '/primerjs-0.0.3-3.tgz   /primerjs-0.0.3.tgz   /0.0.3-16'))
rx = r'(?:\d+\.)+\d*(?!tgz)'
print(re.findall(rx, '/primerjs-0.0.3-3.tgz   /primerjs-0.0.3.tgz   /0.0.3-16'))

Output:

['0.0.3', '0.0.3', '0.0.3']
['0.0.3', '0.0.3', '0.0.3']
Sign up to request clarification or add additional context in comments.

Comments

1

using parenthesis create object groups. here I selected the 0 group that means give me the whole match

the code:

text = '/primerjs-0.0.9.tgz'
...: m = [x.group(0) for x in re.finditer(r"(\d+\.)+\d*(?!tgz)", text)]
...: print m[0]
'0.0.9'

a better approach is to use search instead of re.findall()

text = '/primerjs-0.0.9.tgz'
   ...: m = re.search(r"(\d+\.)+\d*(?!tgz)", text).group(0)
   ...: print m
'0.0.9'

you can even add named group for clarity:

text = '/primerjs-0.0.9.tgz'
...: m = re.search(r"(?P<version>(\d+\.)+\d*(?!tgz))", text).group('version')
...: print m
'0.0.9'

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.