[英]find string with format '[number]' using regex
我在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'
请注意,仅括号中的数字受影响。 我对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)
仍然可以进行编译。
使用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'
由于这里没有其他人跳进来,因此我将为您提供非Python版本的regex
\[(\d{1,8})\]
现在,在替换零件中,您可以使用“被动组” $ n进行替换(其中n =括号中对应于零件的数字)。 这一个是$ 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.