RegEx Conditional Match Match?

I would like to match part of a string with lookarounds, but only if other words are not contained in the string.

Some bears live and eat in the forest.

in the line above, I would like to find β€œeat in” (between β€œlive” and β€œforests”):

/(?<=\blive and\b).*?(?=\bwoods\b)/ 

but only if the "bears" are not separated from the line, neither after, nor before, nor between them.

Other examples of strings 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 regex?

+4
source share
3 answers

This is problematic because most flavors do not support variable-length look, so you cannot check the entire string. A simple approach is to match the entire string, rather than using search queries:

 ^(?!.*\bbears\b).*?\blive and\b(.*?)\bwoods\b 

Here, first of all, was the first coincidence. Depending on what you use, you can replace this text with a little less convenient. Remember to use the muliline flag ( /m ), and not 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 the lines with \bbears\b and match the required line.

+4
source

In Perl:

 use strict; use warnings; my $a = "Some bears live and eat in the woods."; #$a = "Some animals live and eat in the woods, like bears."; $a = "Some animals live and eat bears in the woods."; $a =~ /(?(?!.*bears.*)(.*\blive and\b(.*)\bwoods\b.*)|(.{0}))/g; print $2; 

The condition ?(?!.*bears.*) similar to

 if the string contains the bears string then matches .*\blive and\b(.*)\bwoods\b.* else matches .{0} 

You don't need inverse mappings to match between live and woods

Read more about Terms of expression here.

+2
source

Your question and examples don't seem to match, but you can do something like:

 (?!.*\bbears\b)(?<=\blive and\b).*?(?=\bwoods\b) 

(just an extended regular expression)

+1
source

All Articles