REGEX - match the Nth word of a line containing a specific word -


i'm trying correct regex task:

match nth word of line containing specific word

for example:

input:

this first line - blue second line - green third line - red 

i want match 7th word of lines containing word «second»

desired output:

green 

does know how this?

i'm using http://rubular.com/ test regex.

i tried out regex without success - matching next line

(.*second.*)(?<data>.*?\s){7}(.*) 

--- updated ---

example 2

input:

this foo line - blue bar line - green test line - red 

i want match 4th word of lines containing word «red»

desired output:

test 

in other words - word want match can come either before or after word use select line

you can use match line containing second , grab 7th word:

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

make sure global , multiline flags active.

^ matches beginning of line.

(?=.*\bsecond\b) positive lookahead make sure there's word second in particular line.

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

(\s+) 7th.

regex101 demo


you can apply same principle other requirements.

with line containing red , getting 4th word...

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

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -