Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java replace regex a-z0-9 only

Tags:

java

regex

I would like to show only a-z0-9 in a string, and the other characters should be replaced by null string

String s=this.saveFileName.replaceAll("/[a-z0-9. ]/", "");

This those not work, any ideas why?

like image 915
lacas Avatar asked Dec 04 '22 11:12

lacas


1 Answers

Try this:

String s = "abc123ABC!@#$%^;'xyz";
String newString = s.replaceAll("[^a-z0-9]", "");
//newString is now "abc123xyz"

This takes advantage of the negation (^) operator in character classes which basically says, "match everything except the following characters."

Also, you don't need slashes when defining Java regexes.

like image 144
Mike Deck Avatar answered Dec 28 '22 08:12

Mike Deck