Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing version number as regular expression

Tags:

python

regex

I need to represent version numbers as regular expressions. The broad definition is

  1. Consist only of numbers
  2. Allow any number of decimal points (but not consecutively)
  3. No limit on maximum number

So 2.3.4.1,2.3,2,9999.9999.9999 are all valid whereas 2..,2.3. is not.

I wrote the following simple regex

'(\d+\.{0,1})+'

Using it in python with re module and searching in '2.6.31' gives

>>> y = re.match(r'(\d+\.{0,1})+$','2.6.31')
>>> y.group(0)
'2.6.31'
>>> y.group(1)
'31'

But if I name the group, then the named group only has 31.

Is my regex representation correct or can it be tuned/improved? It does not currently handle the 2.3. case.

like image 394
RedBaron Avatar asked Feb 21 '23 21:02

RedBaron


1 Answers

The notation {0,1} can be shortened to just ?:

r'(\d+\.?)+$'

However, the above will allow a trailing .. Perhaps try:

r'\d+(\.\d+)*$'

Once you have validated the format matches what you expect, the easiest way to get the numbers out is with re.findall():

>>> ver = "1.2.3.4"
>>> re.findall(r'\d+', ver)
['1', '2', '3', '4']
like image 122
Greg Hewgill Avatar answered Mar 03 '23 14:03

Greg Hewgill