Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What regex can I use to match only letters, numbers, and one space between each word?

Tags:

How can I create a regex expression that will match only letters and numbers, and one space between each word?

Good Examples:

 Amazing  Hello World  I am 500 years old 

Bad Examples:

 Hello  world  I am 500 years      old.  I    am   Chuck Norris 
like image 569
Alon Gubkin Avatar asked Oct 27 '09 12:10

Alon Gubkin


People also ask

How do you regex only letters?

To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters.

How do you specify a space in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

What does \b mean in regular expressions?

Simply put: \b allows you to perform a “whole words only” search using a regular expression in the form of \bword\b. A “word character” is a character that can be used to form words. All characters that are not “word characters” are “non-word characters”.

What is the difference between \b and \b in regular expression?

appears on your color - coded pass-key. Using regex \B-\B matches - between the word color - coded . Using \b-\b on the other hand matches the - in nine-digit and pass-key . How come in the first example we use \b to separate cat and in the second use \B to separate - ?


2 Answers

([a-zA-Z0-9]+ ?)+? 
like image 44
brysseldorf Avatar answered Sep 28 '22 10:09

brysseldorf


Most regex implementations support named character classes:

^[[:alnum:]]+( [[:alnum:]]+)*$ 

You could be clever though a little less clear and simplify this to:

^([[:alnum:]]+ ?)*$ 

FYI, the second one allows a spurious space character at the end of the string. If you don't want that stick with the first regex.

Also as other posters said, if [[:alnum:]] doesn't work for you then you can use [A-Za-z0-9] instead.

like image 179
John Kugelman Avatar answered Sep 28 '22 09:09

John Kugelman