0

I'm trying to wrap my head around regular expressions, and still can't figure one thing out.

Let's say we have this string:

const text = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'

If I use text.match(/(dog)([^]+)(lazy)/), it gives me dog. If the dog reacted, was it really lazy".

Instead I'm trying to get something like this: "dog reacted, was it really lazy".

How do I format the regular expression, to get the shortest match between the first and the second word?

IcyFoxe
  • 13
  • 1
  • 2
  • You should prevent matching dog again until you match lazy `\bdog\b(?:(?!\bdog\b).)*\blazy\b` https://regex101.com/r/5Ve9Jz/1 See this page about [Tempered Greedy Token](https://stackoverflow.com/questions/30900794/tempered-greedy-token-what-is-different-about-placing-the-dot-before-the-negat) – The fourth bird Jul 05 '21 at 11:05
  • Try `\bdog\b(?:(?!\bdog\b)[^.])*?\blazy\b` – anubhava Jul 05 '21 at 11:05
  • 1
    Thank you very much for help. Non-capturing group is what I was missing. However I need to use capturing group instead of boundary, because I can't guarantee that the search term will be separated by spaces. So this worked for me `(dog)(?:(?!(dog))[^])+?(lazy)`. – IcyFoxe Jul 05 '21 at 11:24

0 Answers0