Mayuran
Mayuran

Reputation: 708

Regular expression for printable ASCII, but not allowing string that all characters are space

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

Answers (3)

Mayuran
Mayuran

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

Avinash Raj
Avinash Raj

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.

DEMO

String s[] = {"foo bar", "    ","bar"};
for(String i:s)
{
    System.out.println(i.matches("(?=[ \\t]*\\S)([!-~]|[ ])*"));
}

Output:

true
false
true

Upvotes: 2

Ravi K Thapliyal
Ravi K Thapliyal

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

Related Questions