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
To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters.
\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.
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”.
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 - ?
([a-zA-Z0-9]+ ?)+?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With