title: Python Regex in Variable
body: <p><strong>Code Iteration #2</strong></p>
  
  <p>Changing var1 to a raw string by using the <code>stringVar = r'string'</code> worked great.  With the code below I am now getting an exception of:</p>
  
  <pre><code>Traceback (most recent call last):
    File "regex_test.py", line 8, in &lt;module&gt;
      pattern = re.compile(var2 + "(.*)")
    File "/usr/lib/python2.7/re.py", line 190, in compile
      return _compile(pattern, flags)
    File "/usr/lib/python2.7/re.py", line 242, in _compile
      raise error, v # invalid expression
  sre_constants.error: unbalanced parenthesis
  </code></pre>
  
  <p>--</p>
  
  <pre><code>#!/usr/bin/python
  
  import re
  
  var1 = r'\\some\String\to\Match'
  var2 = '\\\\some\\String\\'
  
  pattern = re.compile(var2 + "(.*)")
  found = pattern.match(var1, re.IGNORECASE)
  
  if found:
      print "YES"
  else:
      print "NO"
  </code></pre>
  
  <hr>
  
  <p>I am trying to include a variable in my regular expression.  This question is related to <a href="https://stackoverflow.com/questions/6930982/variable-inside-python-regex">this other question</a>, but differs slightly by using a compiled pattern vs the variable within the match.  According to everything I've read, the example code below should work.</p>
  
  <pre><code>#!/usr/bin/python
  
  import re
  
  var1 = re.escape('\\some\String\to\Match') # A windows network share
  var2 = "\\\\some\\String\\"
  
  print var1 # Prints \\some\\String\ o\\Match
  print var2 # Prints \\some\String\
  
  pattern = re.compile(var2)
  found = pattern.match(var1 + "(.*)", re.IGNORECASE)
  
  if found:
      print "YES"
  else:
      print "NO"
  </code></pre>
  
  <p>When I print out my variables I am seeing some weird behavior.  I thought the re.escape would escape all needed chars within a string.</p>
  
  <p>When I execute the code in Python 2.7 on Ubuntu 12.4.1 I get the following exception </p>
  
  <pre><code>Traceback (most recent call last):
    File "regex_test.py", line 11, in &lt;module&gt;
      pattern = re.compile(var2)
    File "/usr/lib/python2.7/re.py", line 190, in compile
      return _compile(pattern, flags)
    File "/usr/lib/python2.7/re.py", line 242, in _compile
      raise error, v # invalid expression
  sre_constants.error: bogus escape (end of line)
  </code></pre>
  
  <p>What am I missing that is causing the exception to be thrown?</p>