-3

My requirement is, I want to match words in a sentence from two groups of words, say the sentence should contain at least one word from group 1 and at least 1 from group 2 as well.

Expression - (football | hockey | cricket) and (ronaldo | messi | kohli | jordan)

The sentence can be - Ronaldo is the highest paid player in Football.

What could be the possible regex for this, language is php.

I tried

(?=.*\b(cat|dog|rat)\b)(?=.*\b(blue|black|red)\b).*$ It works but is case sensitive.

CinCout
  • 9,486
  • 12
  • 49
  • 67
AbhikM
  • 77
  • 2
  • 10

2 Answers2

1

Use the following:

.*\b(?:ronaldo|messi|kohli|jordan)\b.*\b(?:football|hockey|cricket)\b.* /i

Note the use of /i flag to match case-insensitively.

Demo

CinCout
  • 9,486
  • 12
  • 49
  • 67
0

Try to use 2 regexes, one per group, and then checkfor 2 matches:

For example:

Forst regex: /(Football)|(Hockey)|(Cricket)/i

Second regex: /(Ronaldo)|(Messi)|(Kohli)|(Jordan)/i

Demo for the First Regex

Demo for the Second Regex

  • 1
    I tried this - (?=.*\b(cat|dog|rat)\b)(?=.*\b(blue|black|red)\b).*$ It works but is cases sensitive. – AbhikM Jul 24 '19 at 08:19
  • The Capital letters can be just in the beginning of the word? –  Jul 24 '19 at 08:26