2

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?

3
  • 1
    It is .NET, use (?<=DOG\[[^][]*?)(?:look|stuff)(?=[^][]*]) Commented May 7, 2020 at 20:12
  • You have no idea how much you've just helped me. Do you mind writing a full-on answer where you can explain your code in a little more detail? I want to understand it a little more. Commented May 7, 2020 at 20:17
  • There are alternatives and workarounds for this, too, but I can't show you any since you have not explained what you plan to do with the matches. Commented May 7, 2020 at 20:44

1 Answer 1

2

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 ].
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.