Home > Back-end >  Regex, how to find lines that contain both specified words?
Regex, how to find lines that contain both specified words?

Time:01-31

how to find lines that contain both specified words - using Regex pattern?

For example, I need find lines, than contains both words 'MExp' and 'Aggregate'.

Thank you.

CodePudding user response:

Well, "both words" is equivalent to "word1...word2" or "word2...word1":

(word1.*word2)|(word2.*word1)

Or, depending on your environment/host language, simply use two regex, e.g. with JavaScript:

if (line.test(/word1/) && line.test(/word2/)) {
  // both words
}

or with grep:

<line.txt grep 'word1' | grep 'word2'

CodePudding user response:

To match 1 word: \b(Aggregate)\b. If you don't have to be super efficient then I would test 2 times.

Also this tool is useful for generating regex fast: regex generator

I could not research this furthermore, but this topic might help you out combined with the word search.

Good luck! ;)

CodePudding user response:

Let's say you have a file.

abcde
fghijk MExp lmnopq Aggregate
fghijk MExp Aggregate lmnopq 
fghijk Aggregate lmnopq MExp 
fghijk Aggregate MExp lmnopq  
xywz

If the order of the words are not relevant, the regex would be

(MExp.*Aggregate)|(Aggregate.*MExp)

If the order is important, use only the applicable one.

MExp.*Aggregate or Aggregate.*MExp

  • Related