Regular Expression Constraint String Size

How to limit string size for this regex?

/^[az][a-z0-9]*(?:_[a-z0-9]+)*$/ 

I just need to add the {3,16} quantifier.

+14
regex
source share
3 answers

Sprinkle in some positive lookahead to check the total length of the string, e.g.

 /^(?=.{3,16}$)[az][a-z0-9]*(?:_[a-z0-9]+)*$/ 
+38
source share

I donโ€™t know why you need this, but you can try to split your expression into 2 lines and link them later. Are you sure there is no other way to check your input? Like an existing library or something else.

0
source share

Use regex

/^[az](?:[az\d]|_(?!_)){1,14}[az\d]$/

or

/^(?=.{3,16}$)[az][az\d]*(?:_[az\d]+)*$/

0
source share

All Articles