Reputation: 83
I've searched and searched and tried many different ways, but I can't seem to figure this out. I'm looking for a way to only allow alphanumeric characters, then only one space, then alphanumeric characters. I'm sure it's easy, but I don't know it.
Examples of what I want:
First Last Allowed First La-st Not Allowed FirstLast Not Allowed First Last Not Allowed First La'st Not allowed
I'd then like to remove the invalid characters from the string.
Please let me know if you need more information. Thanks a lot!
Upvotes: 7
Views: 4565
Reputation: 26
this will work perfectly for alphanumeric and only one space between them if applicable
@"^[a-zA-Z0-9]+([ ]{0,1}[a-zA-Z0-9]+)*$"
it will allow like values
anand
anand dev
anand123
anand123 dev
123anand
123anand dev123
my user name is anand123
anand123 dev **Not allowed due to multiple space**
anand dev **not allowed due to space at begining**
Hope this will help you. Thanks.
Upvotes: 0
Reputation: 43703
I believe you don't want numbers in names and you are looking for this regex:
^\p{L}+ \p{L}+$
or
^\p{L}+\s\p{L}+$
where \p{L}+
matches one or more "letter" characters, so not just a-z
and A-Z
, but also other languages' characters. For example, Élise Wilson.
If you really want just alphanumeric characters and input should have two sections with one space between; and invalid characters has to be removed, then:
[^\s\dA-Za-z]+
with an empty string,^\s*
with an empty string,\s*$
with an empty string, and^[\da-zA-Z]+ [\da-zA-Z]+$
To exclude numbers from string remove \d
from above patterns.
To allow longer space between, not just one space character, add +
behind space character in first pattern or behind \s
in the second one.
Upvotes: 1
Reputation: 56779
This should do it:
^[0-9a-zA-Z]+ [0-9a-zA-Z]+$
Demo: http://jsfiddle.net/5m6RH/
Upvotes: 6