rsp
rsp

Reputation: 869

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?

Upvotes: 1

Views: 1904

Answers (3)

Thomas K
Thomas K

Reputation: 40370

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.

Upvotes: 4

Keng
Keng

Reputation: 53111

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

Upvotes: 0

Adam Rosenfield
Adam Rosenfield

Reputation: 400454

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'

Upvotes: 1

Related Questions