user1006115
user1006115

Reputation: 279

java regex: word chracters and white spaces

I'd like to combine the \w and \s classes. So the input should only contain letters, numbers and whitespaces.

I've already tried "[\\w\\s]" and "\\w\\s" and others. But they don't work.

Thanks in advance!

Upvotes: 0

Views: 1571

Answers (3)

tchrist
tchrist

Reputation: 80384

You need (?U)[\p{alnum}\s], under Java 7. Otherwise it gets both those sets wrong, because it only works on ASCII otherwise.

Upvotes: 2

Paul Vargas
Paul Vargas

Reputation: 42020

Try this:

^[\w\s&&[^_]]+$

\w other than letters and numbers, also inclues underscore. You need to do a subtraction if don't want it.

  • For abc abc 123: YES
  • For abc_abc 123: NO

Upvotes: 0

Pshemo
Pshemo

Reputation: 124225

Try maybe (\\w|\\s) to combine it. It means \\w OR \\s, but for me

    System.out.println("abc def ghi".replaceAll("[\\w\\s]", "X"));
    //out ->            XXXXXXXXXXX

works fine

Upvotes: 0

Related Questions