Generating regex string to be used in re.match()
<p>I am trying to a string to be used as regex String.<br>
In the following code: <br>
<code>_pattern</code> is a pattern like <code>abba</code> and I am trying to check <code>_string</code> follows the <code>_pattern</code> (eg. <code>catdogdogcat</code>)<br></p>

<p><code>rxp</code> in the following code is the regular expression that I am trying to create to match to <code>_string</code> (eg. for above example it will be <code>(.+)(.+)\\2\\1</code> ). Which is being successfully generated. But the <code>re.match()</code> is returning <code>None</code>. <br><br>
I want to understand why it is not working and how to correct it ? </p>

<pre><code>import re

_pattern = "abba" #raw_input().strip()
_string = "catdogdogcat" #raw_input().strip()
hm = {}
rxp = ""
c = 1
for x in _pattern:
    if hm.has_key(x):
        rxp += hm[x]
        continue
    else:
        rxp += "(.+)"
        hm[x]="\\\\"+str(c)
        c+=1

print rxp
#print re.match(rxp,_string) -&gt; (Tried)  Not working
#print re.match(r'rxp', _string) -&gt; (Tried) Not working

print re.match(r'%s' %rxp, _string) # (Tried) Not working 
</code></pre>

<p><strong>Output</strong> <br>
<code>(.+)(.+)\\2\\1
None</code></p>

<p><strong>Expected Output</strong><br>
<code>(.+)(.+)\\2\\1
&lt;_sre.SRE_Match object at 0x000000000278FE88&gt;
</code></p>

<p>You should use string formatting, and not hard-code <code>rxp</code> into the string:</p>

<pre><code>print re.match(r'%s'%rxp, _string)
</code></pre>

python regex