Skip to content Skip to sidebar Skip to footer

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 [

Solution 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

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

Post a Comment for "How To Replace Only The Contents Within Brackets Using Regular Expressions?"