Reputation: 7202
I have a string:
s = 'This is a number -N-'
I want to substitute the -N-
placeholder for a regular expression:
s = 'This is a number (\d+)'
So I can later use s
as a regular expression to match against another string:
re.match(s, 'This is a number 2')
However, I'm not able to get s to substitute in a regular expression that doesn't escape the slash:
re.sub('-N-', r'(\d+)', 'This is a number -N-')
# returns 'This is a num (\\d+)'
Please let me know what I'm doing wrong here. Thanks!
Upvotes: 2
Views: 121
Reputation: 250921
Your string contains only single \
, use print
to see the actual string output:
str
version:
>>> print re.sub(r'-N-', r'(\d+)', 'This is a number -N-')
This is a number (\d+)
repr
versions:
>>> re.sub(r'-N-', r'(\d+)', 'This is a number -N-')
'This is a number (\\d+)'
>>> print repr(re.sub(r'-N-', r'(\d+)', 'This is a number -N-'))
'This is a number (\\d+)'
so, your regex is going to work fine:
>>> patt = re.compile(re.sub(r'-N-', r'(\d+)', 'This is a number -N-'))
>>> patt.match('This is a number 20').group(1)
'20'
>>> regex = re.sub(r'-N-', r'(\d+)', 'This is a number -N-')
>>> re.match(regex, 'This is a number 20').group(1)
'20'
For more info: Difference between __str__ and __repr__ in Python
Upvotes: 4