Reputation: 23
I need to create a Regular Expression for 13 characters alphanumeric string having exactly 3 characters and 10 numbers.
I am trying this:
^(?=.*\d{10})(?=.*[a-zA-Z]{3})[0-9a-zA-Z]{13}$
but its not working.
Upvotes: 2
Views: 3694
Reputation: 891
If order doesn't matter, I believe this should work:
/^(?=.{13}$)(\d*([A-Z]\d*){3})$/ig
or
/^(?=.{13}$)([0-9]*([a-zA-Z][0-9]*){3})$/g
This breaks down as follows:
^
: Start of string(?=.{13}$)
: Look ahead expression - this looks ahead to find something (in this case 13 characters then the end of a string) before going on to do the actual RegEx\d*
: Find any number of 0-9 (\d is equivalent to [0-9])([A-Z]\d*){3}
: Find one A-Z then any number of 0-9 (x3 to find your three alphas)$
: End of stringi
: Ignore caseg
: Find globalUpvotes: 5
Reputation: 60494
Try this (with case insensitive and ^$ matches newline options set
(?=^[a-z0-9]{13}$)([a-z]*[0-9][a-z]*){10}
or
(?=^[a-z0-9]{13}$)([^0-9]*[0-9][^0-9]*){10}
Ensure only 13 characters in the string, and only letters or digits
Look for exactly 10 digits in the string
EDIT was to change from three digits to ten digits.
Regex Explanation
(?=^[a-z0-9]{13}$)(?:[^0-9]*[0-9][^0-9]*){10}
Options: Case insensitive; Exact spacing; Dot doesn't match line breaks; ^$ match at line breaks; Parentheses capture
Ensure line is exactly 13 characters, with only letters and digits
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=^[a-z0-9]{13}$)»
Assert position at the beginning of a line (at beginning of the string or after a line break character) (line feed) «^»
Match a single character present in the list below «[a-z0-9]{13}»
Exactly 13 times «{13}»
A character in the range between “a” and “z” (case insensitive) «a-z»
A character in the range between “0” and “9” «0-9»
Assert position at the end of a line (at the end of the string or before a line break character) (line feed) «$»
Ensure there are exactly ten digits in the line
Match the regular expression below «(?:[^0-9]*[0-9][^0-9]*){10}»
Exactly 10 times «{10}»
Match any single character NOT in the range between “0” and “9” «[^0-9]*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match a single character in the range between “0” and “9” «[0-9]»
Match any single character NOT in the range between “0” and “9” «[^0-9]*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Created with RegexBuddy
Upvotes: 1
Reputation: 6721
This is inelegant, but it works for all my tests:
/^(?=[\da-zA-Z]{13}$)(?=([^a-zA-Z]*[a-zA-Z]){3})(?!([^a-zA-Z]*[a-zA-Z]){4})(?=(\D*\d){10})(?!(\D*\d){11}).*$/
Just ask if it works for you and you want an explanation, or else please provide a test case where it does not work correctly
Upvotes: 0