Regular Expression to match only letters numbers and spaces

17,840

Solution 1

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

Solution 2

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
Share:
17,840
aygeta
Author by

aygeta

Updated on August 15, 2022

Comments

  • aygeta
    aygeta over 1 year

    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?