Skip to content Skip to sidebar Skip to footer

Representing Version Number As Regular Expression

I need to represent version numbers as regular expressions. The broad definition is Consist only of numbers Allow any number of decimal points (but not consecutively) No limit on

Solution 1:

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']

Solution 2:

Alternatively, you might want to use pyparsing:

>>> from pyparsing import *
>>> integer = Word(nums)
>>> parser = delimitedList(integer, delim='.') + StringEnd()
>>> list(parser.parseString('1.2.3.4'))
['1', '2', '3', '4']

or lepl:

>>> from lepl import *
>>> with Separator(~Literal('.')):
...    parser = Integer()[1:]
>>> parser.parse('1.2.3.4')
['1', '2', '3', '4']

Post a Comment for "Representing Version Number As Regular Expression"