Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all but certain characters from a string in Java? [duplicate]

Assume you had a string "ACcwerwervwvrwBq^2424 /.* DffGZ..'B". How would you only keep certain characters like A,B,C,D and remove the rest?

string.replaceAll seems to work if I know what characters to remove, but I want to remove all characters except A,B,C,D. Putting every character in there except those 4 seems pretty tedious, what the easier way?

I want the output in the above case to be "ACBDB".

like image 383
Citut Avatar asked Jan 30 '23 10:01

Citut


1 Answers

You would use regex something like:

str.replaceAll("[^ABCD]", "");

Should do it

like image 144
Dale Avatar answered Jan 31 '23 23:01

Dale