Subramanyam Samarjit
Subramanyam Samarjit

Reputation: 35

regex to set the group length in python

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

Answers (2)

Abhijit
Abhijit

Reputation: 63707

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

^(?=[\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

Anshul Rai
Anshul Rai

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

Related Questions