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


i have string:

s = 'this number -n-' 

i want substitute -n- placeholder regular expression:

s = 'this number (\d+)' 

so can later use s regular expression match against string:

re.match(s, 'this number 2') 

however, i'm not able s substitute in regular expression doesn't escape slash:

re.sub('-n-', r'(\d+)', 'this number -n-') # returns 'this num (\\d+)' 

please let me know i'm doing wrong here. thanks!

your string contains single \, use print see actual string output:

str version:

>>> print re.sub(r'-n-', r'(\d+)', 'this number -n-') number (\d+) 

repr versions:

>>> re.sub(r'-n-', r'(\d+)', 'this number -n-') 'this number (\\d+)' >>> print repr(re.sub(r'-n-', r'(\d+)', 'this number -n-')) 'this number (\\d+)' 

so, regex going work fine:

>>> patt = re.compile(re.sub(r'-n-', r'(\d+)', 'this number -n-')) >>> patt.match('this number 20').group(1) '20' >>> regex = re.sub(r'-n-', r'(\d+)', 'this number -n-') >>> re.match(regex, 'this number 20').group(1) '20' 

for more info: difference between __str__ , __repr__ in python


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -