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 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.
The notation
{0,1}can be shortened to just?:However, the above will allow a trailing
.. Perhaps try:Once you have validated the format matches what you expect, the easiest way to get the numbers out is with
re.findall():