0

I am solving a problem where I need to match different case insensitive permutations of a given word in the target string.

For example :

word to match : cAda

target string : AbrAcadAbRa

Here, 2 possible permutations that can be found in the target string S are Acad and cadA.

I have written something like this :

    String pattern = "" ;

    for(char ch : word.toCharArray()){
        pattern = pattern + "(?=[\\s\\S]*(" + ch + "))" ;
    }
    pattern = "^" + pattern + "*$";

    Pattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);

It does not work.

Raghvendra Kumar
  • 1,328
  • 1
  • 10
  • 26

1 Answers1

0

Regular expression is not the best tool for this task. You would have to generate a new regular expression for every input word. Not impossible, but overly complicated.

You'd be better off sorting the letters of the target word, then for each n-length substring of the input word, sort the letters and see if they match the sorted target word.

So, given the target word "cAda", you sort it to give "Aacd".

The user inputs "AbrAcadAbRa"

So you take the first 4-letter substring, "AbrA", sort it to get "AAbr", and check it against the sorted target. No match. Then take "brAc", sort it, and check. Then "Acad", etc.

There are some potential optimizations to avoid the sorting, but with small strings they probably don't matter very much.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351