简体   繁体   中英

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 replace 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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