in reply to Can I have a hard stop on a match
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.
|
|---|