Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The notion that regex doesn't support inverse matching is not entirely true. You can mimic this behavior by using negative look-arounds:</p> <pre><code>^((?!hede).)*$ </code></pre> <p>The regex above will match any string, or line without a line break, <strong>not</strong> containing the (sub)string 'hede'. As mentioned, this is not something regex is "good" at (or should do), but still, it <em>is</em> possible. </p> <p>And if you need to match line break chars as well, use the <a href="http://perldoc.perl.org/perlre.html#Modifiers" rel="noreferrer">DOT-ALL modifier</a> (the trailing <code>s</code> in the following pattern):</p> <pre><code>/^((?!hede).)*$/s </code></pre> <p>or use it inline:</p> <pre><code>/(?s)^((?!hede).)*$/ </code></pre> <p><em>(where the <code>/.../</code> are the regex delimiters, i.e., not part of the pattern)</em></p> <p>If the DOT-ALL modifier is not available, you can mimic the same behavior with the character class <code>[\s\S]</code>:</p> <pre><code>/^((?!hede)[\s\S])*$/ </code></pre> <h2>Explanation</h2> <p>A string is just a list of <code>n</code> characters. Before, and after each character, there's an empty string. So a list of <code>n</code> characters will have <code>n+1</code> empty strings. Consider the string <code>"ABhedeCD"</code>:</p> <pre><code> ┌──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┐ S = │e1│ A │e2│ B │e3│ h │e4│ e │e5│ d │e6│ e │e7│ C │e8│ D │e9│ └──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┘ index 0 1 2 3 4 5 6 7 </code></pre> <p>where the <code>e</code>'s are the empty strings. The regex <code>(?!hede).</code> looks ahead to see if there's no substring <code>"hede"</code> to be seen, and if that is the case (so something else is seen), then the <code>.</code> (dot) will match any character except a line break. Look-arounds are also called <em>zero-width-assertions</em> because they don't <em>consume</em> any characters. They only assert/validate something. </p> <p>So, in my example, every empty string is first validated to see if there's no <code>"hede"</code> up ahead, before a character is consumed by the <code>.</code> (dot). The regex <code>(?!hede).</code> will do that only once, so it is wrapped in a group, and repeated zero or more times: <code>((?!hede).)*</code>. Finally, the start- and end-of-input are anchored to make sure the entire input is consumed: <code>^((?!hede).)*$</code></p> <p>As you can see, the input <code>"ABhedeCD"</code> will fail because on <code>e3</code>, the regex <code>(?!hede)</code> fails (there <em>is</em> <code>"hede"</code> up ahead!).</p>
 

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