2

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!

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Neil
  • 7,042
  • 9
  • 43
  • 78

2 Answers2

4

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

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • I'm not able to take the result of the re.sub() and apply it as a regular expression on the subsequent re.match. Can you verify that it works? – Neil Aug 28 '13 at 13:15
-1

Why not just use a replace?

 s.replace('-N-','(\d+)')
Lorcan O'Neill
  • 3,303
  • 1
  • 25
  • 24