Asqiir Asqiir - 4 years ago 75
Python Question

find substrings and replace them but get their information [python]

I want to do something like this to a text (This is just an example to show the problem):

new_text = re.sub(r'\[(?P<index>[0-9]+)\]',
'(Found pattern the ' + index + ' time', text)


Where text is my original text. I want to find any substring like this:
[3]
or
[454]
. But this isn't the hard part. The hard part is to get the number in there. I want to use the number to use a method called
add_link(number)
which expects a number(instead of the string I'm building with "Found pattern..." - that's just an example). (In a database it has stored links matched to IDs where it finds the links.)

Python tells me it doesn't know the local variable
index
. How can I make it knowing?

Edit: I have been told I didn't ask clearly. (I already have an answer but maybe someone is going to read this in future.) The question was how to get the pattern known as
[0-9]+
get as a local variable. I guessed it would be something like this:
(?P<index>[0-9]+)
, and it was.

Thanx in advanced, Asqiir

Answer Source

You can reference a named group in the replacement string with the syntax \g<field name>. So your code should be written as:

new_text = re.sub(r'\[(?P<index>[0-9]+)\]', '(Found pattern the \g<index> time', text)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download