开发者

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]. This includes the brackets and x, where x is any number between 1 and several million. I then need to repla开发者_运维百科ce x with my own string.

ie, 'Some string [3423] of words and numbers like 9898' would turn into '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 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:

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:

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

\[(\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). This one would be $1

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜