Can somebody please show me how to do a Java regex that takes in a string and returns a st开发者_StackOverflow中文版ring with all characters removed BUT a-z and 0-9?
I.e. given a string a%4aj231*9.+
it will return a4aj2319
thanks.
\d is digit, \p{L} is a-z and A-Z.
str.replaceAll("[^\\d\\p{L}]", "");
str = str.replaceAll("[^a-z0-9]+", "");
If you also meant to include uppercase characters, then you could use
str = str.replaceAll("[^A-Za-z0-9]+", "");
or the slightly leeter
str = str.replaceAll("[_\\W]+", "");
If you want a-z and 0-9 but not A-Z then
str.replaceAll("[^\\p{Lower}\\p{Digit}]", "");
精彩评论