How to replace only the contents within brackets u

2019-03-02 09:21发布

问题:

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.

回答1:

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



回答2:

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]'