• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java regex to count non alphanumeric characters in a String

 
Aditya Sirohi
Ranch Hand
Posts: 93
Eclipse IDE Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
21
IntelliJ IDE Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could have a Regex for a non-alphanumeric character then use find() in a loop to see how many times it comes back.
 
Aditya Sirohi
Ranch Hand
Posts: 93
Eclipse IDE Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Steve. I got it.
 
Aditya Sirohi
Ranch Hand
Posts: 93
Eclipse IDE Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wanted to share this now:

 
Darryl Burke
Bartender
Posts: 5126
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would replace all alphanumeric characters with the empty String and take the length() of the result.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic