aspose file tools*
The moose likes Beginning Java and the fly likes java regex to count non alphanumeric characters in a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "java regex to count non alphanumeric characters in a String" Watch "java regex to count non alphanumeric characters in a String" New topic
Author

java regex to count non alphanumeric characters in a String

Aditya Sirohi
Ranch Hand

Joined: Jan 05, 2010
Posts: 93

Hi All,

Is there a way to use Java Regex to count number of non alphanumeric characters in the String.

For example:
a1b2c3$3# should return 2

I have something like this:
Pattern p = Pattern.compile(".*\\W+.*");
Matcher m = p.matcher(test);

But this returns if String contains non alphanumeric characters and not the count.

Any help or suggestion is appreciated.
Thanks,
Aditya
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

You could have a Regex for a non-alphanumeric character then use find() in a loop to see how many times it comes back.


Steve
Aditya Sirohi
Ranch Hand

Joined: Jan 05, 2010
Posts: 93

Thanks Steve. I got it.
Aditya Sirohi
Ranch Hand

Joined: Jan 05, 2010
Posts: 93

I wanted to share this now:

Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4642
    
    5

I would replace all alphanumeric characters with the empty String and take the length() of the result.


luck, db
There are no new questions, but there may be new answers.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: java regex to count non alphanumeric characters in a String