Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to match only letters numbers and spaces

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?

like image 819
aygeta Avatar asked Jan 29 '12 10:01

aygeta


People also ask

How do I allow only letters and numbers in regex?

You can use regular expressions to achieve this task. In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".

How do you match letters in regex?

Using character sets For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


2 Answers

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
like image 171
Tim Pietzcker Avatar answered Oct 17 '22 21:10

Tim Pietzcker


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
like image 22
Guffa Avatar answered Oct 17 '22 20:10

Guffa