I use python 2.7
I just try to change a group in a regex with a value:
import re
r = "/foo/bar/(?P<pk>[0-9]+)/"
rc = re.compile(r)
#that i try to do : rc["pk"] = 42 and get the resut
print rc.groupindex
#return {'pk' : 1}
I need to do this because i don't know the regex, but I know that ther is a group in it.
Edit:
I want to have a result like this:
rc["pk"] = 42
#now rc is /foo/bar/42 because (?P<pk>[0-9]+) is replace with 42
I am not a python programmer, but I work with regexes a great deal in a number of other systems. I believe you can use the re.sub
function with backreferences to groups like so:
Search Pattern:
'(/foo/bar/)[0-9]+(/)'
Replacement pattern:
'\g<1>42\g<2>'
This would replace
'/foo/bar/17/'
with
'/foo/bar/42/'
This would even work where the folder names are expressions themselves:
'(/\w+/\w+/)\d+(/)'
Python also supports lookaround statements, like this:
'(?<=/foo/bar/)\d+(?=/)'
Then you just replace the match with '42'
. (Lookarounds do not "consume" characters, so the text in '((?<=...)'
and '(?=...)'
would not be replaced.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.