简体   繁体   English

使用正则表达式查找格式为“ [number]”的字符串

[英]find string with format '[number]' using regex

I have a string in a django/python app and need to search it for every instance of [x] . 我在django / python应用程序中有一个字符串,需要在[x]每个实例中搜索它。 This includes the brackets and x, where x is any number between 1 and several million. 这包括方括号和x,其中x是1到几百万之间的任何数字。 I then need to replace x with my own string. 然后,我需要用自己的字符串替换x。

ie, 'Some string [3423] of words and numbers like 9898' would turn into 'Some string [mycustomtext] of words and numbers like 9898' 也就是说, 'Some string [3423] of words and numbers like 9898'将变成'Some string [mycustomtext] of words and numbers like 9898'

Note only the bracketed number was affected. 请注意,仅括号中的数字受影响。 I am not familiar with regex but think this will do it for me? 我对regex不熟悉,但是认为这对我有用吗?

Regex is precisely what you want. 正则表达式正是您想要的。 It's the re module in Python, you'll want to use re.sub, and it will look something like: 它是Python中的re模块,您将要使用re.sub,它将类似于:

newstring = re.sub(r'\[\d+\]', replacement, yourstring)

If you need to do a lot of it, consider compiling the regex: 如果您需要做很多事情,请考虑编译正则表达式:

myre = re.compile(r'\[\d+\]')
newstring = myre.sub(replacement, yourstring)

Edit: To reuse the number , use a regex group: 编辑: 要重新使用数字 ,请使用正则表达式组:

newstring = re.sub(r'\[(\d+)\]',r'[mytext, \1]', yourstring)

Compilation is still possible too. 仍然可以进行编译。

Use re.sub : 使用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'

Since no one else is jumping in here I'll give you my non-Python version of the regex 由于这里没有其他人跳进来,因此我将为您提供非Python版本的regex

\[(\d{1,8})\]

Now in the replacement part you can use the 'passive group' $n to replace (where n = the number corresponding to the part in parentheses). 现在,在替换零件中,您可以使用“被动组” $ n进行替换(其中n =括号中对应于零件的数字)。 This one would be $1 这一个是$ 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM