Walker
Walker

Reputation: 353

Match just the result of a capture group with regex?

Basically I want to search for something and get a capture group, then ignore the search and get results that match that capture group.

So if I have this text:

apples are good
bananas are bad
oranges are good

I want oranges
I want bananas
I want apples

I'd want to search (\w+) are good, and then search I want \1 to get I want apples and I want oranges.

How would I do this in one expression?

(sorry for the poor explanation)

Upvotes: 4

Views: 75

Answers (1)

James Skirving
James Skirving

Reputation: 64

This will do it:

/.*?(\w+?)\sare\sgood.*?(\w+?)\sare\sgood.*(I\swant\s(\1|\2)).*(I\swant\s(\1|\2))/s

It's a bit hacky since it will only work on the provided text, as far as I know there isn't a way to grab all occurrences of 'I want' for each occurrence of 'are good' using a single regex.

Upvotes: 1

Related Questions