cattarantadoughan
cattarantadoughan

Reputation: 509

Regex to find words in order but in between other words

I have a problem implementing a regex for a particular scenario.

Lets say the input is "the brown dog" to be searched from "the quick brown fox jumps over the lazy dog". It should return true with the following conditions:

  1. -not case sensitive
  2. -must be in order (1st word is 'the', 2nd is 'brown', 3rd is 'dog').

This means inputs like "the dog brown", "fox brown", "the quick fox brown" would return false but "the dog", "quick brown", "jumps over the" return true. I hope i provided enough samples.

So far my regex "(?i)(?:\\S+\\s)?\\S*"+targetString+"\\S*(?:\\s\\S+)?" only works for exact strings but not in between other words.

Upvotes: 2

Views: 94

Answers (1)

Minato
Minato

Reputation: 4533

String reg = "";
for(String s:targetString.split(' '))
   reg+= s + "(\\s|\\S)*";
//Compile reg as regex and match using pattern

look at this

Upvotes: 1

Related Questions