Reputation: 1
New to Regular Expressions. Thanks in advance!
Need to validate field is 1-10 mixed-case alphanumeric and spaces are allowed. First character must be alphanumeric, not space.
Good Examples:
"Larry King"
"L King1"
"1larryking"
"L"
Bad Example:
" LarryKing"
This is what I have and it does work as long as the data is exactly 10 characters. The problem is that it does not allow less than 10 characters.
[0-9a-zA-Z][0-9a-zA-Z ][0-9a-zA-Z ][0-9a-zA-Z ][0-9a-zA-Z ][0-9a-zA-Z ][0-9a-zA-Z ][0-9a-zA-Z ][0-9a-zA-Z ][0-9a-zA-Z ]
I've read and tried many different things but am just not getting it.
Thank you,
Justin
Upvotes: 0
Views: 2347
Reputation: 1014
i think the simplest way is to go with \w[\s\w]{0,9}
Note that \w
is for [A-Za-z0-9_]
so replace it by [A-Za-z0-9]
if you don't want _
Note that \s
is for any white char so replace it by if you don't want the others
Upvotes: 0
Reputation: 89557
I assume that the space is not allowed at the end too.
^[a-zA-Z0-9](?:[a-zA-Z0-9 ]{0,8}[a-zA-Z0-9])?$
or with posix character classes:
^[[:alnum:]](?:[[:alnum:] ]{0,8}[[:alnum:]])?$
Upvotes: 0
Reputation: 4906
I don't know what environment you are using and what engine. So I assume PCRE (typically for PHP)
this small regex does exact what you want: ^(?i)(?!\s)[a-z\d ]{1,10}$
What's going on?!
^
marks the start of the string (delete it, if the expression must not match the whole string)(?i)
tells the engine to be case insensitive, so there's no need to write all letter lower and upper case in the expression later(?!\s)
ensures the following char won't be a white space (\s
) (it's a so called negative lookahead)[a-z\d ]{1,10}
matches any letter (a-z
), any digit (\d
) and spaces (
) in a row with min 1 and max 10 occurances ({1,10}
)$
at the end marks the end of the string (delete it, if the expression must not match the whole string) Here's also a small visualization for better understanding.
Upvotes: 1
Reputation: 3446
The below is probably most semantically correct:
(?=^[0-9a-zA-Z])(?=.*[0-9a-zA-Z]$)^[0-9a-zA-Z ]{1,10}$
It asserts that the first and last characters are alphanumeric and that the entire string is 1 to 10 characters in length (including spaces).
Upvotes: 0
Reputation: 1
Try this: ^[(^\s)a-zA-Z0-9][a-z0-9A-Z ]*
Not a space and alphanumeric for the first character, and then zero or more alphanumeric characters. It won't cap at 10 characters but it will work for any set of 1-10 characters.
Upvotes: 0
Reputation: 151
You want something like this.
[a-zA-Z0-9][a-zA-Z0-9 ]{0,9}
This first part ensures that it is alphanumeric. The second part gets your alphanumeric with a space. the {0,9} allows from anywhere from 0 to 9 occurrences of the second part. This will give your 1-10
Upvotes: 0
Reputation: 51330
Try this: [0-9a-zA-Z][0-9a-zA-Z ]{0,9}
The {x,y}
syntax means between x
and y
times inclusive. {x,}
means at least x
times.
Upvotes: 0