nbaplaya
nbaplaya

Reputation: 103

Regexp pattern with any single character without white-spaces

private Pattern pattern = Pattern.compile(".");

This pattern works for me in both cases:

  1. when there is only one character
  2. when there is only one character + a lot of white spaces (new lines, spaces)

How to change this to ignore white spaces? So valid is:

"a"

And not valid:

" a", "    a    ", "\n     a"

Upvotes: 0

Views: 63

Answers (3)

Bohemian
Bohemian

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

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

basic regex features:

  • anchors ^, $ to ensure the character matched is the first and the last in input
  • character set [..] to specify wanted characters or [^..] for unwanted characters

Note 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

Lothar
Lothar

Reputation: 5459

\S is "not a whitespace", so your regex could be something like this:

^\S$

Upvotes: 3

Related Questions