-2

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

Asqiir
  • 607
  • 1
  • 8
  • 23
  • 2
    Your question is not clear. Please describe the issue with an example. Also, before posting the question you should read it once and see whether if you were the person answering the question, would you be able to understand it and answer it? – Moinuddin Quadri Feb 05 '17 at 20:49
  • Why is my question marked as duplicate? The given link (the question, whose duplicate this is he said) doesn't answer to my question. (Which is: how to get the local variable.) – Asqiir Feb 05 '17 at 21:10
  • Then you should edit the question and clearly explain your issue. Right now it is not clear. – Moinuddin Quadri Feb 05 '17 at 21:11

1 Answers1

0

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)
davidedb
  • 867
  • 5
  • 12