Reputation: 11
I have following two strings
root = 'svn\\456'
dir = 'svn\\456\\765'
pattern = re.compile('^'+root)
matched = pattern.match(dir)
I always get matched None. But if I do like following
root = 'svn\\456'
dir = 'svn\456\\765'
pattern = re.compile('^'+root)
matched = pattern.match(dir)
I get matched as True.
sorry if its a really basic thing which I am missing here. But I am just starting with python.
Thanks.
Upvotes: 1
Views: 53
Reputation: 627607
You have a literal string that you are trying to use to create a regex object. It contains a special regex character that must be escaped.
You need to use re.escape
function for that.
Here is an IDEONE demo:
import re
root = r'svn\456'
dir = r'svn\456\765'
pattern = re.compile('^'+re.escape(root))
matched = pattern.match(dir)
print(matched)
Upvotes: 0
Reputation: 53565
The problem with using 'svn\\456'
as a pattern is that \
is a special character that requires escaping, so if you'll change the first pattern to: 'svn\\\\456'
you'll get a match:
import re
root = 'svn\\\\456'
dir = 'svn\\456\\765'
pattern = re.compile('^'+root)
matched = pattern.match(dir) # matched!
Upvotes: 1