Python - REGEX issue with RE using function re.compile + search
<p>I'm using regex library 're' in Python (2.7) to validate a flight number.</p>

<p>I've had no issues with expected outputs using a really helpful online editor here: <a href="http://regexr.com/" rel="nofollow">http://regexr.com/</a></p>

<p>My results on regexr.com are: <a href="http://imgur.com/nB0QDug" rel="nofollow">http://imgur.com/nB0QDug</a></p>

<p>My code is:</p>

<pre><code>import re
test1 = 'ba116'
###Referencelink: http://academe.co.uk/2014/01/validating-flight-codes/
p = re.compile('/^([a-z][a-z]|[a-z][0-9]|[0-9][a-z])[a-z]?[0-9]{1,4}[a-z]?$/g')
m = p.search(test1)  # p.match() to find from start of string only
if m:
print 'It works!: ', m.group()  # group(1...n) for capture groups
else:
print 'Did not work'
</code></pre>

<p>I'm unsure why I get the 'didn't work' output where regexr shows one match (as expected)</p>

<p>I made a much simpler regex lookup, and it <em>seemed</em> that the results were correct, so it seems either my regex string is invalid, or I'm using re.complile (or perhaps the if loop) incorrectly?</p>

<p>'ba116' is valid, and should match.</p>

<p>Python's <code>re.compile</code> is treating your leading <code>/</code> and trailing <code>/g</code> as part of the regular expression, not as delimiters and modifiers.  This produces a compiled RE that will never match anything, since you have <code>^</code> with stuff before it and <code>$</code> with stuff after it.</p>

<p>The first argument to <code>re.compile</code> should be a string containing <em>only</em> the stuff you would put inside the slashes in a language that had <code>/.../</code> regex notation.  The <code>g</code> modifier corresponds to calling the <code>findall</code> method on the compiled RE; in this case it appears to be unnecessary.  (Some of the other modifiers, e.g. <code>i</code>, <code>s</code>, <code>m</code>, correspond to values passed to the <em>second</em> argument to <code>re.compile</code>.)</p>

<p>So this is what your code should look like:</p>

<pre><code>import re
test1 = 'ba116'
###Referencelink: http://academe.co.uk/2014/01/validating-flight-codes/
p = re.compile(r'^([a-z][a-z]|[a-z][0-9]|[0-9][a-z])[a-z]?[0-9]{1,4}[a-z]?$')
m = p.search(test1)  # p.match() to find from start of string only
if m:
    print 'It works!: ', m.group()  # group(1...n) for capture groups
else:
    print 'Did not work'
</code></pre>

<p>The <code>r</code> immediately before the open quote makes no difference for <em>this</em> regular expression, but if you needed to use backslashes in the RE it would save you from having to double all of them.</p>

python regex if-statement