Alejandro Simkievich
Alejandro Simkievich

Reputation: 3792

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

'Blue Wire Connectors '

can anyone suggest how to build this regex in python?

Upvotes: 0

Views: 1413

Answers (2)

user2390182
user2390182

Reputation: 73470

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.

Upvotes: 1

user2705585
user2705585

Reputation:

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

Upvotes: 1

Related Questions