Márcio
Márcio

Reputation: 57

JAVA - REGEX - Don't match only whitespaces

I'm trying to build a regular expression that doesn't allow only whitespaces, but, for example, does allow

"    aaaaa    "
"      aaaaa"
"aaaaaa       "

The string's lenght should be {1,150}.

I'm trying to use

^(?=.\\S).{1,20}$

...but it doesn't work for the input of

"    aaaaaa"

Upvotes: 2

Views: 465

Answers (4)

progrenhard
progrenhard

Reputation: 2363

^(.*[^\s].*){1,150}$

Regular expression visualization

Debuggex Demo

Upvotes: 0

Michelle
Michelle

Reputation: 2900

I would check the contents and length separately. Apply a regex to check if the string contains at least one non-whitespace character at any position:

\S

And then check the length with:

myString.length() >= 1 && myString.length() <= 150

Upvotes: 0

anubhava
anubhava

Reputation: 785156

You can use this regex:

^(?!\s+$).{1,150}$

Upvotes: 2

celeritas
celeritas

Reputation: 2281

This is a regular expression to match between 1 and 150 non-whitespace characaters that are optionally sandwiched with whitespace:

^\s*\S{1,150}\s*$

Upvotes: 1

Related Questions