Note that there are some explanatory texts on larger screens.

plurals
  1. PORegex: negative look-ahead between two matches
    primarykey
    data
    text
    <p>I'm trying to build a regex somewhat like this:</p> <pre><code>[match-word] ... [exclude-specific-word] ... [match-word] </code></pre> <p>This seems to work with a negative look-ahead, but I'm running into a problem when I have a case like this:</p> <pre><code>[match-word] ... [exclude-specific-word] ... [match-word] ... [excluded word appears again] </code></pre> <p>I want the above sentence to match, but the negative look-ahead between the first and the second matched word "spills over" so the second word is never matched. </p> <p>Let's look at a practical example. </p> <p>I wan't to match every sentence which has the word "i" and the word "pie", but not the word "hate" in between those two words. I have these three sentences:</p> <pre><code>i sure like eating pie, but i love donuts &lt;- Want to match this i sure like eating pie, but i hate donuts &lt;- Want to match this i sure hate eating pie, but i like donuts &lt;- Don't want to match this </code></pre> <p>I have this regex:</p> <pre><code>^i(?!.*hate).*pie - have removed the word boundaries for clarity, original is: ^i\b(?!.*\bhate\b).*\bpie\b </code></pre> <p>Which matches the first sentence, but not the second one, because the negative look-ahead scans the whole string.</p> <p>Is there a way to limit the negative look-ahead, so that it's satisfied if it encounters "pie" before it encounters "hate"?</p> <p>Note: in my implementation, there may be other terms following this regex (it's built dynamically from a grammar search engine), for instance:</p> <pre><code>^i(?!.*hate).*pie.*donuts </code></pre> <p>I'm currently using JRegex, but could probably switch to JDK Regex if necessary</p> <p><strong>Update</strong>: I forgot to mention something in my initial question:</p> <p>It's possible that the "negative construct" exists further in the sentence, and I do want to match the sentence if it's possible even if the "negative" construct exists further up.</p> <p>To clarify, look at these sentences:</p> <pre><code>i sure like eating pie, but i love donuts &lt;- Want to match this i sure like eating pie, but i hate donuts &lt;- Want to match this i sure hate eating pie, but i like donuts &lt;- Don't want to match this i sure like eating pie, but i like donuts and i hate making pie &lt;- Do want to match this </code></pre> <p>rob's answer works perfectly for this extra constraint, so I'm accepting that one.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload