Mostly technical stuff with some interesting moments of life

Java Regex: Check for non word characters

I wanted to test a given string to see if it contains any non word characters in Java. Initially I came up with a lengthy version ;) Then after a bit of search I could simply shorten it.

Version1: regular expression


Version2: regular expression


Here's a nice guide ( to start with Java regular expressions


  1. Does not work for string with more than one non-word character distributed through the string e.g. "word&&word&&word" will fail.

    The Pattern ".*\\W+.*" covers this case

  2. Thanks Patrick. In fact I used this to validate key strokes. That's why I didn't catch the issue you have pointed out.