Reputation: 35
I have a version 'major.minor.patch'
major version range [0-99999]
minor version range [0-9999]
patch version range [0-999999]
but on the whole 'major.minor.path' should not exceed 16 characters including . (dot).
I have tried the following reg expression
^(\d{1,5}[.]\d{1,4}[.]\d{1,6}){1,16}$
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
(\d{1,5}[.]\d{1,4}[.]\d{1,6})
Upvotes: 3
Views: 1796
Reputation: 63707
You have two regular expressions here that you want to combine
^[\d.]{,16}$
^\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
^(?=[\d.]{,16}$)\d{1,5}[.]\d{1,4}[.]\d{1,6}$
Example:
exp = r'^(?=[\d.]{,16}$)\d{1,5}[.]\d{1,4}[.]\d{1,6}$'
vers = ['111.111.111',
'111111.1111.1111',
'11111.1111.111111',
'11111.1111.11111']
["{} Matches ? {}".format(v, "YES" if re.match(exp, v) else "NO" )
for v in vers]
Output
['111.111.111 Matches ? YES',
'111111.1111.1111 Matches ? NO',
'11111.1111.111111 Matches ? NO',
'11111.1111.11111 Matches ? YES']
Upvotes: 3
Reputation: 782
Add a lookahead at the beginning that allows a match only if its within 1-16 range by using a $
to anchor at the end: (?=^.{1,16}$)
Upvotes: 1