Code Iteration #2
Changing var1 to a raw string by using the stringVar = r'string'
worked great. With the code below I am now getting an exception of:
Traceback (most recent call last):
File "regex_test.py", line 8, in <module>
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
--
#!/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"
I am trying to include a variable in my regular expression. This question is related to this other question, 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.
#!/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"
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.
When I execute the code in Python 2.7 on Ubuntu 12.4.1 I get the following exception
Traceback (most recent call last):
File "regex_test.py", line 11, in <module>
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)
What am I missing that is causing the exception to be thrown?