Neil
Neil

Reputation: 7202

Python: substituting a regular expression into a string to be used as a regular expression

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

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

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

Lorcan O'Neill
Lorcan O'Neill

Reputation: 3393

Why not just use a replace?

 s.replace('-N-','(\d+)')

Upvotes: -1

Related Questions