How to match the Nth word of a line containing a specific word using regex

regex

Solution

You can use this to match a line containing `second` and grab the 7th word:

^(?=.*\bsecond\b)(?:\S+ ){6}(\S+)

Make sure that the global and multiline flags are active.

`^` matches the beginning of a line.

`(?=.*\bsecond\b)` is a positive lookahead to make sure there's the word `second` in that particular line.

`(?:\S+ ){6}` matches 6 words.

`(\S+)` will get the 7th.

regex101 demo

You can apply the same principle with other requirements.

With a line containing `red` and getting the 4th word...

^(?=.*\bred\b)(?:\S+ ){3}(\S+)

Problem

I'm trying to do to get the correct regular expression to match the Nth word of a line containing a specific word. For example, if I have this input: ``` this is the first line - blue this is the second line - green this is the third line - red ``` I want to match the seventh word of the lines containing the word "second" and return `green`. I'm using Rubular to test the regular expression. I already tried out this regular expression without success - it is matching the next line: ``` (.*second.*)(?<data>.*?\s){7}(.*) ``` Another example input: ``` this is the Foo line - blue this is the Bar line - green this is the Test line - red ``` I want to match the fourth word of the lines containing the word "red" and return `Test`. The word I want to match can come either before or after the word I use to select the line.

Original source