Chris
Chris

Reputation: 5804

How to replace only the contents within brackets using regular expressions?

How to replace only the contents within brackets using regular expressions?

String = "This is my string [123]"

I want to replace 123 with 456

Desired_String = "This is my string [456]"

My attempt:

regex = '.*\[(.*?)\].*'
re.sub(regex,'456',String)
>> 456

I'm not sure what regex to use so that it replaces the 123 with 456.

Upvotes: 3

Views: 10016

Answers (2)

Jerry
Jerry

Reputation: 71538

If you modify your regex and your replacement string a little, you get it:

regex = '\[.*?\]'
re.sub(regex,'[456]',String)

You don't need to match the entire string with .* for the substitution to work.

Also, it's not entirely required here, but it's good practice to raw your regex strings:

regex = r'\[.*?\]'
        ^

Another option would be to use negated classes, which will be faster as well!

regex = r'[^\[\]]+(?=\])'
re.sub(regex,'456',String)

It might be a little confusing, but [^\[\]]+ matches any character except [ and ].

regex101 demo

Upvotes: 7

Sven Marnach
Sven Marnach

Reputation: 601679

Alternatively, you could use look-ahead and look-behind assertions (documentation):

>>> regex = r'(?<=\[).*?(?=\])'
>>> re.sub(regex, '456', 'This is my string [123]')
'This is my string [456]'

Upvotes: 4

Related Questions