I have to validate a String
with only white spaces. In my String
white spaces between a String
is allowed but only white spaces not allowed. For example "conditions apply"
,"conditions"
etc is allowed but not " "
. ie, only white space not allowed
I want a regular expression in JavaScript for this
I have to validate a String
with only white spaces. In my String
white spaces between a String
is allowed but only white spaces not allowed. For example "conditions apply"
,"conditions"
etc is allowed but not " "
. ie, only white space not allowed
I want a regular expression in JavaScript for this
Share Improve this question edited Jan 7, 2013 at 14:03 RP89 asked Jan 7, 2013 at 12:36 RP89RP89 1412 gold badges5 silver badges16 bronze badges5 Answers
Reset to default 7Try this regular expression
".*\\S+.*"
Do you really need to use a regex?
if (str.trim().length() == 0)
return false;
else
return true;
As mentionned in the ments, this could be simplified to a one-liner
return str.trim().length() > 0;
or, since Java 6
return !str.trim().isEmpty();
you can do it like this:
// This does replace all whitespaces at the end of the string
String s = " ".trim();
if(s.equals(""))
System.out.println(true);
else
System.out.println(s);
what about checking if the string does not match "\\s+"
?
The regular expression is ^\\s*$
is used to match a whitespace only string, you can validate against this.
^ # Match the start of the string
\\s* # Match zero of more whitespace characters
$ # Match the end of the string
Anchoring to the start and the end of the string is important here.