使用正则表达式查找格式为'[数字]'的字符串
我在一个django/python的应用里有一个字符串,我需要在这个字符串中找到所有像 [x]
这样的部分。这里的 [x]
包括方括号和里面的数字,x可以是1到几百万之间的任何数字。接着,我需要把这个x替换成我自己的字符串。
比如,'Some string [3423] of words and numbers like 9898'
这个字符串应该变成 'Some string [mycustomtext] of words and numbers like 9898'
。
注意,只有带括号的数字被替换了。我对正则表达式不太熟悉,但我觉得这样做可以实现我的需求?
3 个回答
0
因为没有其他人来回答,我就给你提供一个不是用Python写的正则表达式版本。
\[(\d{1,8})\]
在替换的部分,你可以使用“被动组” $n 来替换(这里的 n 是指括号里对应的部分的数字)。这个例子中就是 $1。
1
使用 re.sub
:
import re
input = 'Some string [3423] of words and numbers like 9898'
output = re.sub(r'\[[0-9]+]', '[mycustomtext]', input)
# output is now 'Some string [mycustomtext] of words and numbers like 9898'
4
正则表达式(Regex)正是你需要的东西。在Python中,它是通过re模块来实现的,你可以使用re.sub这个功能,代码大概是这样的:
newstring = re.sub(r'\[\d+\]', replacement, yourstring)
如果你需要做很多这样的操作,可以考虑先编译一下正则表达式:
myre = re.compile(r'\[\d+\]')
newstring = myre.sub(replacement, yourstring)
补充说明:如果想重复使用某个数字,可以使用正则表达式的分组功能:
newstring = re.sub(r'\[(\d+)\]',r'[mytext, \1]', yourstring)
编译也是可以的。