Skip to content Skip to sidebar Skip to footer

Python - Not Sure How To Build Following Regex

I want to replace 'this is my string (anything within brackets)' with 'this is my string ' a concrete sample would be: 'Blue Wire Connectors (35-Pack)' should be replaced with '

Solution 1:

The pattern to be replaced should look about like that: r'\(.*?\)' which matches bracketed expressions non-greedily in order to avoid matching multiple bracketed expressions as one (Python docs):

import re

s = 'this (more brackets) is my string (anything within brackets)'
x = re.sub(r'\(.*?\)', '', s)
# x: 'this  is my string '

Note, however, that nested brackets 'this (is (nested))' are a canonical example that cannot be properly handled by regular expressions.

Post a Comment for "Python - Not Sure How To Build Following Regex"