Accepted answer:
String commonChars = s.replaceAll("[^"+t+"]","");
has an error !!!
What if string t has a regular expression metacharacter? In this case, replaceAll fails.
See this program for an example, where the string t has ] in it and ] is a regular expression metacharacter that marks the end of the character class. Obviously, the program does not display the expected result.
Why?
Consider:
String s = "1479K"; String t = "459LP]";
Now the regex will become (just replace t ):
String commonChars = s.replaceAll("[^459LP]]","");
Which says to replace any character other than 4 , 5 , 9 , L , P , followed by ] with nothing. This is clearly not what you want.
To fix this, you need to avoid ] in t . You can do it manually as:
String t = "459LP\\]";
and regex works fine .
This is a common problem when using regex, so the java.util.regex.Pattern class provides a static method called quote that can be used for this: quote regular expression metacharacters so that they are processed literally.
So before using t in replaceAll you specify it as:
t = Pattern.quote(t);
A program using the quotation method works as expected.
codaddict
source share