So suppose I have:
String s = "1479K";
String t = "459LP";
and I want to return
String commonChars = "49";
the common characters between the two strings.
Obviously it is possible to do with a standard loop like:
String commonChars = "";
for (i = 0; i < s.length; i++)
{
char ch = s.charAt(i);
if (t.indexOf(ch) != -1)
{
commonChars = commonChars + ch;
}
}
However I would like to be able to do this in one line using replaceAll
. This can be done as follows:
String commonChars = s.replaceAll("["+s.replaceAll("["+t+"]","")+"]","");
My question is: is it possible to do this using a single invocation of replaceAll
? And what would be the regular expression? I presume I have to use some sort of lookahead, but my brain turns to mush when I even think about it.