Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Thanks for the answers. I feel each answer had part of the answer. Here is what I was looking for.</p> <ol> <li><p><strong>?</strong> symbol is just a shorthand for <strong>(something|&epsilon;)</strong>. Thus <strong>(a|&epsilon;)</strong> can be rewritten as <strong>a?</strong>. So the example becomes:</p> <pre><code>b*(abb*)*a? </code></pre> <p>In python we would write:</p> <pre><code>p = re.compile(r'^b*(abb*)*a?$') </code></pre></li> <li><p>The reason straight translation of regular regular expression syntax into python (i.e. copy and paste) does not work is because python matches the <em>shortest substring</em> (if the symbols $ or ^ are absent) while the theoretical regular expressions match <em>longest initial substring</em>. <br/> So for example if we had a string:</p> <pre><code>s = 'aa' </code></pre> <p>Our textbook regex <strong>b*(abb*)*a?</strong> would not match it because it has two a's. However if we copy it straight to python:</p> <pre><code>&gt;&gt; p = re.compile(r'b*(abb*)*a?') &gt;&gt; bool(p.match(s)) True </code></pre> <p>This is because our regex matches only the substring 'a' of our string 'aa'. <br/> In order to tell python to do a match on the whole string we have to tell it where the beginning and the end of the string is, with the <strong>^</strong> and <strong>$</strong> symbols respectively:</p> <pre><code>&gt;&gt; p = re.compile(r'^b*(abb*)*a?$') &gt;&gt; bool(p.match(s)) False </code></pre> <p>Note that python regex <strong>match()</strong> matches at the <em>beginning</em> of the string, so it automatically assumes the <strong>^</strong> at the start. However the <strong>search()</strong> function does not, and thus we keep the <strong>^</strong>.<br/> So for example:</p> <pre><code>&gt;&gt; s = 'aa' &gt;&gt; p = re.compile(r'b*(abb*)*a?$') &gt;&gt; bool(p.match(s)) False # Correct &gt;&gt; bool(p.search(s)) True # Incorrect - search ignored the first 'a' </code></pre></li> </ol>
 

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