Reputation: 11
So i have a string (with spaces):
John Doe
That can be mixed with up to 10 numbers
John Doe 123456789
In no particular order:
1234john Doe567890
I've tried mixing chars, spaces and numbers like this:
([A-Za-z ])([0-9]){10}
But i doesn't hit the target
How can i write a Regex to validate that?
Upvotes: 0
Views: 258
Reputation:
Try this
^(?=(?:\D*\d){0,10}\D*$)
Explained:
^ # Beginning of string, BOS
# Lookahead assertion
(?=
# Note this group is designed
# so that it is the only place
# a digit can exist.
(?: # Group
\D* # Optional, any amount of non-digits
\d # Required, a single digit
){0,10} # End group, do 0 to 10 times
# Example:
# - If this group runs 0 times, no digits were in the string.
# - If this group runs 4 times, 4 digits are in the string.
# - Therefore, min digits = 0, max digits = 10
\D* # Finally, and optionally, any amount of non-digits
$ # End of string, EOS
)
Upvotes: 2
Reputation: 626738
You may use
^(?:[A-Za-z ]*[0-9]){0,10}[A-Za-z ]*$
Details
^
- start of string(?:[A-Za-z ]*[0-9]){0,10}
- zero to ten occurrences of
[A-Za-z ]*
- 0 or more spaces or letters[0-9]
- a digit[A-Za-z ]*
- 0 or more spaces or letters$
- end of string.If there must be at least 1 digit, use
^(?:[A-Za-z ]*[0-9]){1,10}[A-Za-z ]*$
^
Upvotes: 0