user558134
user558134

Reputation: 1129

Regular expression limit string size

How to limit string size for this regular expression?

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

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

Upvotes: 27

Views: 38807

Answers (3)

NARESH RAMINI
NARESH RAMINI

Reputation: 33

[\w\d]{2,18}

\w: matches a-z, A-Z, and underscores. \d: matches 0-9 numbers. 2: Minium two characters required. 18: Maximum allowed characters 18.

Upvotes: 1

buckley
buckley

Reputation: 14129

Sprinkle in some positive lookahead to test for the total length of the string by adding

(?=.{3,16}$)

at the start of the regex. The final regex is then:

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

Upvotes: 69

Ωmega
Ωmega

Reputation: 43703

Use regex

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

or

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

Upvotes: 0

Related Questions