Subramanyam Gundam Subramanyam Gundam - 1 year ago 62
Python Question

regex to set the group length in python

I have a version 'major.minor.patch'

major version range


minor version range

patch version range

but on the whole 'major.minor.path' should not exceed 16 characters including . (dot).
I have tried the following reg expression


but {1,16} means 1 to 16 repetitions of previous expression not the length of previous group
How can I make the length of following group to 16


Answer Source

You have two regular expressions here that you want to combine

  1. ^[\d.]{,16}$
  2. ^\d{1,5}[.]\d{1,4}[.]\d{1,6}$

Both in itself is invalid as (1) can match more than 2 dots and the individual length limits on each version are not honoured. (2) definitely does not work as it exceeds the string length limit of 16 characters including '.'

A less known feature of regex lookhead can be used to combine(and-ed) both the above regex expressions which would be something like



exp = r'^(?=[\d.]{,16}$)\d{1,5}[.]\d{1,4}[.]\d{1,6}$'
vers = ['111.111.111', 
["{} Matches ? {}".format(v, "YES" if re.match(exp, v) else "NO" ) 
 for v in vers]


['111.111.111 Matches ? YES', 
 '111111.1111.1111 Matches ? NO', 
 '11111.1111.111111 Matches ? NO', 
 '11111.1111.11111 Matches ? YES']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download