Skip to content
Advertisement

Regex limit the number of letters total in the entire string

I have this expression which is almost what I need:

/(?=^.{5,12}$)(^[a-zA-Zu0590-u05fe]{0,4}[0-9]{3,8}[a-zA-Zu0590-u05fe]{0,4}$)/

except, I need to only allow 4 letters total (4 in the beginning and 0 in the end,3 and 1, 2 and 2, 0 and 4, etc…)

allowed inputs: 11abcd11 1abcdefg123 abcd1234

unallowed inputs: 1abcd11 abcd123 1abcd12

is there a way to achieve this? thanks!

Advertisement

Answer

To make sure there are exactly four letters in the string, you can use

^(?=.{5,12}$)(?=(?:[^a-zA-Zu0590-u05fe]*[a-zA-Zu0590-u05fe]){4}[^a-zA-Zu0590-u05fe]*$)[a-zA-Zu0590-u05fe]{0,4}[0-9]{3,8}[a-zA-Zu0590-u05fe]{0,4}$

See the regex demo

The (?=(?:[^a-zA-Zu0590-u05fe]*[a-zA-Zu0590-u05fe]){4}[^a-zA-Zu0590-u05fe]*$) positive lookahead makes sure there are four sequences of any zero or more “non-letters” followed with a “letter” and then there are zero or more “non-letters” till the end of string.

If you can target ECMAScript 2018+ compliant engines you can use a Unicode-aware version:

/^(?=.{5,12}$)(?=(?:P{L}*p{L}){4}P{L}*$)p{L}{0,4}[0-9]{3,8}p{L}{0,4}$/u

See this regex demo, where p{L} matches letters. You may also replace it with p{Alphabetic} which also matches letters that are Roman numbers.

Advertisement