[英]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.其中 text 是我的原文。 I want to find any substring like this:
[3]
or [454]
.我想找到任何这样的子字符串:
[3]
或[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).我想使用数字来使用名为
add_link(number)
的方法,该方法需要一个数字(而不是我使用“找到的模式...”构建的字符串——这只是一个例子)。 (In a database it has stored links matched to IDs where it finds the links.) (在数据库中,它存储了与找到链接的 ID 匹配的链接。)
Python tells me it doesn't know the local variable index
. Python 告诉我它不知道局部变量
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. (我已经有了答案,但也许将来有人会读到这个。)问题是如何获得称为
[0-9]+
get 作为局部变量的模式。 I guessed it would be something like this: (?P<index>[0-9]+)
, and it was.我猜它会是这样的:
(?P<index>[0-9]+)
,确实如此。
Thanx in advanced, Asqiir感谢先进,Asqiir
You can reference a named group in the replacement string with the syntax \\g<field name>
.您可以使用语法
\\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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.