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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
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: 3943
    
  17

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: 4522
    
    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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: java regex to count non alphanumeric characters in a String
 
Similar Threads
help requested with regular expressions
Regex Help
Regex
Validation using Regular Expressions??
Pattern String to validate that a String contains a number or not