Regex (.NET) to find a pattern between two other patterns

Viewed 40

I have a string that looks something like this:

DOG[i want to look for specific hits of stuff here]

I want to match any occurrences of the words "look" or "stuff" that occur between the opening DOG[ and the closing ]

I know I can write a rege like (?<=DOG\[).*?(?=\]) to find all text between the opening and closing bits, but I want to look for only specific words between these openers and closers.

How can I do this?

1 Answers

Since in .NET regex you may use patterns matching strings of unknown length in lookbehinds, you may use

(?<=DOG\[[^][]*?)(?:look|stuff)(?=[^][]*])

See the regex demo.

Here,

  • (?<=DOG\[[^][]*?) - a positive lookbehind that matches a location immediately preceded with DOG[ and any 0+ chars other than [ and ]
  • (?:look|stuff) - look or stuff
  • (?=[^][]*]) - a positive lookahead that matches a location immediately followed with any 0+ chars other than [ and ] and then a ].
Related