Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>This is a regex that defines "valid" lines:</p> <p><code>/^[A|B]{1}|[C|D]{1}|[E|F]{1}|[G|H]{1}$/m</code> </p> <p>In english, each line has either A or B at position 0, either C or D at position 1, either E or F at position 2, and either G or H at position 3. I can assume that each line will be exactly 4 characters long.</p> </blockquote> <p>That's not what that regex means. That regex means that each line has either A or B or a pipe at position 0, C or D or a pipe at position 1, etc; <code>[A|B]</code> means "either 'A' or '|' or 'B'". The '|' only means 'or' <em>outside</em> of character classes. </p> <p>Also, <code>{1}</code> is a no-op; lacking any quantifier, everything has to appear exactly once. So a correct regex for the above English is this:</p> <pre><code>/^[AB][CD][EF][GH]$/ </code></pre> <p>or, alternatively:</p> <pre><code>/^(A|B)(C|D)(E|F)(G|H)$/ </code></pre> <p>That second one has the side effect of capturing the letter in each position, so that the first captured group will tell you whether the first character was A or B, and so on. If you don't want the capturing, you can use non-capture grouping:</p> <pre><code>/^(?:A|B)(?:C|D)(?:E|F)(?:G|H)$/ </code></pre> <p>But the character-class version is by far the usual way of writing this.</p> <p>As to your problem, it is ill-suited to regular expressions; by the time you deconstruct the string, stick it back together in the appropriate regex syntax, compile the regex, and do the test, you would probably have been much better off just doing a character-by-character comparison. </p> <p>I would rewrite your "ACFG" regex thus: <code>/^(?:AC|A.F|A..G|.CF|.C.G|..FG)$/</code>, but that's just appearance; I can't think of a better solution using regex. (Although as Mike Ryan indicated, it would be better still as <code>/^(?:A(?:C|.E|..G))|(?:.C(?:E|.G))|(?:..EG)$/</code> - but that's still the same solution, just in a more efficiently-processed form.)</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