Reputation: 103
private Pattern pattern = Pattern.compile(".");
This pattern works for me in both cases:
How to change this to ignore white spaces? So valid is:
"a"
And not valid:
" a", " a ", "\n a"
Upvotes: 0
Views: 63
Reputation: 425168
Either:
if (str.matches("\\S")) // don't need ^ and $ in the regex with matches()
or just
if (str.length() == 1 && !Character.isWhitespace(str.charAt(0)))
Upvotes: 0
Reputation: 19315
basic regex features:
^
, $
to ensure the character matched is the first and the last in input[
..]
to specify wanted characters or [^
..]
for unwanted charactersNote that in a string the backslashes have a special meaning and must be doubled to have a literal \
in regex which has also a special meaning \n
for new line character
Pattern.compile("^[^ \\n]$");
Upvotes: 0
Reputation: 5459
\S
is "not a whitespace", so your regex could be something like this:
^\S$
Upvotes: 3