The general problem with the regex is that . matches any character (because you've used /s), and that .+ is by default greedy, that is, it will match as many times as possible. Have a look at perlretut (pay attention to mentions of "greed").

One way to solve this is to change the dot . to an expression that says "match anything except this". For single characters, one could use a negated character class, as in [^a-z]* which will match any characters except lowercase ASCII letters. For longer strings, one way to do it is with a negative lookahead: (?:(?!not|these|strings).)* will give you the "hard stop" you want.

You've only provided one example string, but when developing regular expressions, the more test cases the better. I showed one way to write tests for regexes here: Re: How to ask better questions using Test::More and sample data. For now I've guessed a few test cases, but you should fill that out. This also works on your long string:

use warnings; use strict; use Test::More; my $regex = qr{ \b INSERT \b (?: # the next thing may not be one of these: (?! \b SELECT \b | \( | \; ) . )+ # match one or more times \b doc \b # target string }imsx; like "INSERT doc (", $regex; like "INSERT INTO doc bar (", $regex; unlike "INSERT foo ( doc", $regex; unlike "INSERT foo SELECT doc", $regex; unlike "INSERT foo ; doc", $regex; done_testing;

Update before posting: Eily already posted something very similar here, I'll post this anyway. Update: Adding \b is a good point. Update 2: Minor edits for clarity.


In reply to Re: Can I have a hard stop on a match by haukex
in thread Can I have a hard stop on a match by BillB

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.