I want to match a String if it contains a maximum of 16 digits and a maximum of 11 characters, but with a maximum of 27 characters in total.
I tried (\d{0,16}\w{0,11}){27}, but it doesn’t seem to work.
Edit :
MATCH: 145214mkjnkj or 1234567891011125abcdefghijk (can be mixed)
DONT MATCH: abababababab123 or 12345678910111213abc
Just get rid of the trailing quantifier, and use anchors to match the beginning and end of the string:
Where
^matches start of string and$matches end of string. Now this will match a string with 0 – 16 digits, followed by 0 – 11 word characters. Keep in mind\wincludes[A-Za-z0-9_], if you want to match just alphabetic characters you can do this:Edit: Since (apparently) digits and characters can be mixed, you can use one regex to test for invalid characters, then do some additional processing to determine if the minimum requirements for each character class are met with another regex, like so:
The first is a check to see if the string contains any invalid characters. If this matches, we know the string is invalid:
Note: The above assumes
\wfor characters, for only alphabetic characters, useA-Za-z.If the above check passes, now we know the string contains only digits and characters, we test to see if it has enough characters by replacing all of the digits with an empty string, and checking if the remaining characters (which are only those in the
\wfamily) are the correct length. Note the use of the by-reference$countparameter, named$replacementshere, which will implicitly tell us how many digits there are in the string while we are checking for how many characters are in the string: