i would like to match a part of the string using lookarounds, but only if other words are not contained in the line.
Some bears live and eat in the woods.
in the above line, i’d like to find ” eat in the ” (between “live and” & “woods):
/(?<=\blive and\b).*?(?=\bwoods\b)/
but only if “bears” isn’t apart of the line, either after, before or between the lookarounds.
other examples of lines that should not return a match are:
Some animals live and eat in the
woods, like bears.Some animals live and eat bears in
the woods.
how can i add this condition to my regular expression?
This is problematic because most flavors do not support a variable length look-behind, so you can’t check the whole line. A simple approach is to match the whole line instead of using lookarounds:
Here, what previously was the whole match is the first capturing group. Depending on your you use it, it may make replacing this text a little less convenient. Make sure to use the muliline flag (
/m), and not the set the single-line flag (dot-all, or/s).Working example: http://rubular.com/r/TuADb2vB4w
Note that the problem becomes very simple if you can solve it in two steps: filter out lines with
\bbears\b, and match the wanted string.