Your problem statement doesn't say which "the" and which "dog" you are interested in. For instance, given the input:
The black dog danced around the sleeping dog.

...and the endpoints of "the" and "dog", it seems you want the minimal coverage. Here is where you need some test cases to demonstrate what you will and won't accept.

The way the regex engine works, if it starts to match, say on "the", it will exhaust all options before moving on the the next "the".

One example might be the string where the endpoints are not repeated inside the string. But the following doesn't work:

my $first = "the"; my $last = "dog"; my $string = "The black dog danced around the sleeping dog." my @matches = $string =~ m/\b($first\b(?!.*?$first.*?)\b$last)\b/g;
There doesn't seem to be a good way to say "I don't want $first anywhere in this part", except to do another match. Combine this with Athanasius's solution:
my $first = "the"; my $last = "dog"; my @strings = ("The black dog danced around the sleeping dog.", "The brown bear leaped over the lazy dog."); for my $string (@strings) { my @match = $string =~ m/(?=\b($first\b.*?\b$last)\b)/gi; for my $match (@match) { my @firsts = $match =~ m/\b($first)\b/gi; my @lasts = $match =~ m/\b($last)\b/gi; if ((@firsts == 1) and (@lasts == 1)) { print "$match\n"; } } } # The black dog # the sleeping dog # the lazy dog

-QM
--
Quantum Mechanics: The dreams stuff is made of


In reply to Re: Pattern matching: Lazy vs. greedy by QM
in thread Pattern matching: Lazy vs. greedy by false_friend

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.