Regex + shortest substring + word preceded by another word

I have the following example

"Foo tells the bar that the bar loves potatoes. The bar tells foo that the bar is not like potatoes."

I want a substring between the potatoes and the previous appearance of the bar. So, in this example, I want the bar to love potatoes, and I also want the bar to not like potatoes as a result. How can I achieve this through one regex? I know that if I applied two separate regular expressions, I could get the results, but I want to know if this is possible with only one regular expression.

Thanks RG

+4
source share
3 answers

Good riddle. This can be solved, just not very beautiful:

echo "Foo tells bar that bar likes potato. Bar tells foo that bar does not like potato." | \
    pcregrep  -o '\bbar\s+(?:(?:(?!bar\b)\w+)\s+)*?potato\b'

(?:...) , . , bar.

+3

Python:

>>> import re
>>> s = "Foo tells bar that bar likes potato. Bar tells foo that bar does not like potato."
>>> re.findall('bar (?:(?! bar ).)+? potato', s)
['bar likes potato', 'bar does not like potato']
+1

, perl:

use strict;
use warnings;

my $str
  = "Foo tells bar that bar likes potato. "
  . "Bar tells foo that bar does not like potato."
;

while ($str =~ m/( bar (?: [^b] | b[^a] | ba[^r] )*?  potato )/xmsg) {
    print STDOUT "$1\n";
}

*? - ( 0 , , . "" http://perldoc.perl.org/perlre.html)

, [^b] | b[^a] | ba[^r] . " " (http://regex.info/) , .

0

All Articles