user1489735
user1489735

Reputation: 83

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

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

Answers (6)

user3820761
user3820761

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

Ωmega
Ωmega

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:

  1. replace all matches of [^\s\dA-Za-z]+ with an empty string,
  2. trim leading spaces by replacing ^\s* with an empty string,
  3. trim trailing spaces by replacing \s*$ with an empty string, and
  4. check/validate such string with regex ^[\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

Cylian
Cylian

Reputation: 11181

This should work

(?i)\b[a-z\d]+ [a-z\d]+\b

Upvotes: 0

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56222

Use this regex:

^[\p{L}\d]+ [\p{L}\d]+$

Upvotes: 5

Ry-
Ry-

Reputation: 225238

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

… should do it.

Upvotes: 13

mellamokb
mellamokb

Reputation: 56779

This should do it:

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

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

Upvotes: 6

Related Questions