7

I am not good at regular expressions.

I dont want to allow any other characters but letters spaces and numbers. Of course the user can enter only letters or only numbers or letters and numbers but not other characters. Also he can put _ between strings example:

Hello_World123 

This can be possible string. Can anyone help and build a regex for me?

4
  • Is the empty string allowed? Are non-ASCII letters/digits allowed? Commented Jan 29, 2012 at 10:36
  • "Can anyone help and buid [sic.] an [sic.] regex for me"? You'd be better off learning regular expressions for yourself rather than expecting the community to write them for you. See the tutorial at regular-expressions.info for starters. Commented Jan 29, 2012 at 10:44
  • @Johnsyweb Sorry but im in hurry and i needed that immediatelly. I will learn them for sure. Thanks =) Commented Jan 29, 2012 at 10:50
  • Presumably you'll be giving Tim commission! Commented Jan 29, 2012 at 10:55

3 Answers 3

15

To ensure that a string only contains (ASCII) alphanumeric characters, underscores and spaces, use

^[\w ]+$ 

Explanation:

^ # Anchor the regex at the start of the string [\w ] # Match an alphanumeric character, underscore or space + # one or more times $ # Anchor the regex at the end of the string 
Sign up to request clarification or add additional context in comments.

Comments

5

Simply this:

^[\w ]+$ 

Explanation:

^ matches the start of the string \w matches any letter, digit, or _, the same as [0-9A-Za-z_] [\w ] is a set that that matches any character in \w, and space + allows one or more characters $ matches the end of the string 

2 Comments

Spaces should be allowed too.
@TimPietzcker: Right, I missed that. Thanks.
-3

you can use [\w \d]+ .You can try at http://gskinner.com/RegExr/

2 Comments

This doesn't allow spaces. And don't recommend w3schools. It's one of the worse resources out there.
Still incorrect. No anchors, and \d is already contained in \w.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.