Lakshman
Lakshman

Reputation: 47

How to modify a regular expression to restrict characters count minimum 8 to maximum 20

I have the following regular expression. Now I want to modify it to restrict characters count from 8 to 20.

Minimum characters count should be 8 and maximum 20

^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{2,6}\)?[\s.-]?\d{3,6}[\s.-]?\d{1,4}$

The current expression accepting the following strings but it shouldn't in my case. The string count should be always greater than 8

123456
1234567

Here are more test cases:

https://regex101.com/r/hDNCkT/1

Upvotes: 0

Views: 52

Answers (1)

Gary
Gary

Reputation: 13912

You can use a positive lookahead to limit the overall length of your match. After the carat, insert (?=.{8,20}$). However, if you need to ensure there are 8-20 digits, you could use (?=(\D*\d){8,20}$) instead.

Example

Upvotes: 2

Related Questions