Geosync
Geosync

Reputation: 23

Regex - How to reject based on string length?

Regex:

^[U][S][A]\d{2}[C][S]\d{3}

It indicates these values are valid:

USA25CS131 (valid)
USA25CS1311 (invalid length)

How do I get it to reject a string that's too long?

Upvotes: 0

Views: 499

Answers (2)

Dog9w23
Dog9w23

Reputation: 34

^\w{1,10}$

That will match on anything 1-10 characters long, ^ means start of the line and $ means end of the line. You can adapt this with your code to produce the results you want.

Given your specific regex I would use ^[U][S][A]\d{2}[C][S]\d{3}$(just adding $ to the end)

Upvotes: 1

cigien
cigien

Reputation: 60218

You can simply anchor the regex at the end with $, like this:

^[U][S][A]\d{2}[C][S]\d{3}$

and now you won't match strings with extra characters at the end.

You can also simplify your regex to this:

^USA\d{2}CS\d{3}$

Upvotes: 5

Related Questions