kai
kai

Reputation: 11

Re: Regex - How do I match a word within the first 10 words of a text?

Consider following string as an Example Text:

This hook rack holds my purse on the wall with no problems. The hooks are elegant-looking, with a brushed metal look that lends itself well to all kinds of decor.

I want to match "metal" but only if it appears in the first 10 words of the text. Is that possible to formulate?

Upvotes: 0

Views: 200

Answers (1)

omijn
omijn

Reputation: 656

Here's another simple solution that should work:

^(?:\w+\s*){0,9}(metal)

From the beginning of the string ^, match at most 9 words followed by the word metal. For example, this would match 3 words followed by metal (metal is the 4th word), or 7 words followed by metal (metal is the 8th word), but not 10 words followed by metal (metal is the 11th word).

Try it here: https://regex101.com/r/tj9oaS/1

Upvotes: 2

Related Questions