Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex: check if word has non alphanumeric characters

Tags:

java

regex

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 ??

like image 958
remo Avatar asked Mar 31 '11 20:03

remo


People also ask

How do you find non alphanumeric characters?

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.

How do you check if a string is alphanumeric or not regex?

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.

How do you remove a non alphanumeric character from a string in Java?

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] .

How do you check if a character in a string is alphanumeric?

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 .


1 Answers

Change your regex to:

.*\\W+.*
like image 65
Alex Avatar answered Oct 04 '22 12:10

Alex