0

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
2
  • 3
    it is not clear (to me at least) exactly what you want to achieve... perhaps you can explain a little more? Commented Feb 1, 2013 at 16:22
  • You need some text to match. rc is just a regex. Commented Feb 1, 2013 at 17:22

1 Answer 1

1

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.