Reputation: 708
I have a regular expression that accept only printable ASCII set as follows.
([!-~]|[ ])*
But i want to reject the string that have everything as space like
" "
Any suggestions?
Thanks in advance
Upvotes: 1
Views: 1351
Reputation: 708
Since i have to use the regular expression in XSD, the following regular expression cannot be used
^(?=[ \\t]*\\S)([!-~]|[ ])*
But i have used the following expression, that seems like working for me. A simple expression without any look ahead
([ ]*([!-~])[ ]*)+
Upvotes: 0
Reputation: 174756
Seems like you want something like this,
"^(?=[ \\t]*\\S)([!-~]|[ ])*"
(?=[ \\t]*\\S)
asserts that there must be atleast one non-space character would present on that particular line.
OR
string.matches("(?=\\s*\\S)([!-~]|[ ])*");
Note that the \\s
matches line breaks also.
String s[] = {"foo bar", " ","bar"};
for(String i:s)
{
System.out.println(i.matches("(?=[ \\t]*\\S)([!-~]|[ ])*"));
}
Output:
true
false
true
Upvotes: 2
Reputation: 51711
If empty strings ""
should also not pass your regex test, then simply String#Trim()
your input before the match. Change your regex quantifier from *
to +
i.e. at least one character is required.
([!-~]|[ ])+
Then empty strings or strings with only spaces will fail to match your regex.
Upvotes: 1