Search code examples
regexgroovy

Regex to find common letters between two strings


I've been searching on Google for a few hours and got a partial solution.

I'm new to both Groovy and regular expressions. I've used regex sporadically over the years, but I am far from comfortable with it.

I've got a simple game that checks how many letters you have in common with a hidden word.

For simplicity's sake, let's say the word is "pan" and the person types "can".

I want the result of the regex to give me "an".

Right now, I've got this partly working by doing this (in Groovy):

// Where "guess" is the user's try and "word" is the word they need to guess.
def expr = "[$word]"
def result = guess.find(expr)

The result string contains only the first matching letter. Anyone have any more elegant solutions? Thanks in advance


Solution

  • Suppose the two strings are s1 and s2 now to find the common string do:

    commonString=s1.replaceAll("[^"+s2+"]","");
    

    and if your word contain meta-character then first do:

    Pattern.quote(s2);
    

    and then

    commonString=s1.replaceAll("[^"+s2+"]","");