Linto
Linto

Reputation: 1282

Regular expression for checking a string, which must contain a space and be alpha numeric

Can any one give the regular expression for checking a string

which must contain a space and be alpha numeric.

Upvotes: 2

Views: 6279

Answers (3)

Staffan Nöteberg
Staffan Nöteberg

Reputation: 4145

In JavaScript you can solve it like this:

if (/^[a-z\d]* [a-z\d]*$/i.test(input)) {
    // Successful match
} else {
    // Fail
}

Notes:

  • The i following the regex means ignore case, i.e. it matchez a-z as well as A-Z
  • The regex says: in the beginning, find zero to many alphanums, then a space and finally zero to many alphanums before the string ends
  • the string you test is input
  • If you want to make sure that there's at least one alphanum before and after the space, then use + instead of *

Upvotes: 4

skabbes
skabbes

Reputation: 900

I'm assuming you want the space to be between two alpha numeric substrings. I have also added \s* to allow for whitespace encasing the alpha-numerics (which judging by your comment is what you actually want)

^\s*[0-9a-zA-Z]+[ ][0-9a-zA-z]+\s*$

Upvotes: 2

sidyll
sidyll

Reputation: 59287

/^[A-Za-z0-9]+ [A-Za-z0-9]+$/

If the space can be at the end or the beginning, change the correspondent + to *.

Upvotes: 0

Related Questions