This is my code to determine if a word contains any non-alphanumeric characters:
  String term = "Hello-World";
  boolean found = false;
  Pattern p = Pattern.Compile("\\W*");
  Matcher m = p.Matcher(term);
  if(matcher.find())
    found = true;
I am wondering if the regex expression is wrong. I know "\W" would matches any non-word characters. Any idea on what I am missing ??
The Alphanumericals are a combination of alphabetical [a-zA-Z] and numerical [0-9] characters, a total of 62 characters, and we can use regex [a-zA-Z0-9]+ to matches alphanumeric characters.
The idea is to use the regular expression ^[a-zA-Z0-9]*$ , which checks the string for alphanumeric characters. This can be done using the matches() method of the String class, which tells whether this string matches the given regular expression.
A common solution to remove all non-alphanumeric characters from a String is with regular expressions. The idea is to use the regular expression [^A-Za-z0-9] to retain only alphanumeric characters in the string. You can also use [^\w] regular expression, which is equivalent to [^a-zA-Z_0-9] .
Python string isalnum() function returns True if it's made of alphanumeric characters only. A character is alphanumeric if it's either an alpha or a number. If the string is empty, then isalnum() returns False .
Change your regex to:
.*\\W+.*
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With