Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to allow alphanumeric, only one space and then alpahnumeric

Tags:

c#

.net

regex

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!

like image 427
user1489735 Avatar asked Jun 28 '12 21:06

user1489735


People also ask

Is space allowed in alphanumeric character?

Alphanumeric characters by definition only comprise the letters A to Z and the digits 0 to 9. Spaces and underscores are usually considered punctuation characters, so no, they shouldn't be allowed.

How do you put a space in a regular expression?

The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.

What do you use in a regular expression to match any 1 character or space?

Use square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.


3 Answers

^[a-zA-Z0-9]+ [a-zA-Z0-9]+$

… should do it.

like image 120
Ry- Avatar answered Sep 20 '22 17:09

Ry-


This should do it:

^[0-9a-zA-Z]+ [0-9a-zA-Z]+$

Demo: http://jsfiddle.net/5m6RH/

like image 24
mellamokb Avatar answered Sep 21 '22 17:09

mellamokb


Use this regex:

^[\p{L}\d]+ [\p{L}\d]+$
like image 42
Kirill Polishchuk Avatar answered Sep 22 '22 17:09

Kirill Polishchuk