Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex to extract version from a string

Tags:

python

regex

The string looks like this: (\n used to break the line)

MySQL-vm
Version 1.0.1

WARNING:: NEVER EDIT/DELETE THIS SECTION

What I want is only 1.0.1 .

I am trying re.search(r"Version+'([^']*)'", my_string, re.M).group(1) but it is not working.

re.findall(r'\d+', version) is giving me an array of the numbers which again I have to append.

How can I improve the regex ?

like image 581
Amby Avatar asked Oct 21 '14 07:10

Amby


3 Answers

Use the below regex and get the version number from group index 1.

Version\s*([\d.]+)

DEMO

>>> import re
>>> s = """MySQL-vm
... Version 1.0.1
... 
... WARNING:: NEVER EDIT/DELETE THIS SECTION"""
>>> re.search(r'Version\s*([\d.]+)', s).group(1)
'1.0.1'

Explanation:

Version                  'Version'
\s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                         more times)
(                        group and capture to \1:
  [\d.]+                   any character of: digits (0-9), '.' (1
                           or more times)
)                        end of \1
like image 157
Avinash Raj Avatar answered Oct 08 '22 08:10

Avinash Raj


You can try with Positive Look behind as well that do not consume characters in the string, but only assert whether a match is possible or not. In below regex you don't need to findAll and group functions.

(?<=Version )[\d.]+

Online demo

Explanation:

  (?<=                     look behind to see if there is:
    Version                  'Version '
  )                        end of look-behind
  [\d.]+                   any character of: digits (0-9), '.' (1 or more times)
like image 39
Braj Avatar answered Oct 08 '22 08:10

Braj


(?<=Version\s)\S+

Try this.Use this with re.findall.

x="""MySQL-vm
  Version 1.0.1

  WARNING:: NEVER EDIT/DELETE THIS SECTION"""

print re.findall(r"(?<=Version\s)\S+",x)

Output:['1.0.1']

See demo.

http://regex101.com/r/dK1xR4/12

like image 33
vks Avatar answered Oct 08 '22 09:10

vks