0

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

'Blue Wire Connectors '

can anyone suggest how to build this regex in python?

Alejandro Simkievich
  • 3,512
  • 4
  • 33
  • 49

2 Answers2

1

Simply search with (\([^)]*\)) and replace with empty string "".

This regex is capturing everything within ( ) until a ) is reached i.e end of parenthesis.

Regex101 Demo

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.

user2390182
  • 72,016
  • 6
  • 67
  • 89