Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression that allows spaces in a string, but not only blank spaces

I need to write a regular expression for form validation that allows spaces within a string, but doesn't allow only white space.

For example - 'Chicago Heights, IL' would be valid, but if a user just hit the space bar any number of times and hit enter the form would not validate. Preceding the validation, I've tried running an if (foo != null) then run the regex, but hitting the space bar still registers characters, so that wasn't working. Here is what I'm using right now which allows the spaces:

^[-a-zA-Z0-9_:,.' ']{1,100}$
like image 417
user699242 Avatar asked Apr 08 '11 19:04

user699242


People also ask

Can you put spaces in regex?

The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.

How do you check if a string only contains spaces?

To check if a string contains only spaces, call the trim() method on the string and check if the length of the result is equal to 0 . If the string has a length of 0 after calling the trim method, then the string contains only spaces. Copied!

Does \w include spaces?

\W means "non-word characters", the inverse of \w , so it will match spaces as well.


1 Answers

It's very simple: .*\S.*

This requires one non-space character, at any place. The regular expression syntax is for Perl 5 compatible regular expressions, if you have another language, the syntax may differ a bit.

like image 72
Roland Illig Avatar answered Dec 21 '22 11:12

Roland Illig