Regular expression to delete data in parentheses

I am trying to remove the bracket areas of these lines below, but I cannot get the regex to work :(

Data:

x (LOC) ds ds (32C) d'ds ds (LeC) ds-d da(LOQ) 12345 (deC) 

Regex tried:

 [ \(\w+\)] 

Regex101:

http://regex101.com/r/bD8fE2

Code example

 items = ["x (LOC)", "ds ds (32C)", "d'ds ds (LeC)", "ds-d da(LOQ)", "12345 (deC)"] for item in items: item = re.sub(r"[ \(\w+\)]", "", item) print item 
+6
source share
2 answers

Remove the square brackets; you do not match the character class:

 item = re.sub(r" \(\w+\)", "", item) 

Demo:

 >>> items = ["x (LOC)", "ds ds (32C)", "d'ds ds (LeC)", "ds-d da(LOQ)", "12345 (deC)"] >>> for item in items: ... print re.sub(r" \(\w+\)", "", item) ... x ds ds d'ds ds ds-d da(LOQ) 12345 

One, but the last example does not have a space before the opening bracket ( ( ) and therefore does not match. You can make the space optional if you need this template too:

 item = re.sub(r" ?\(\w+\)", "", item) 

Perhaps something that is not a closing bracket will work for you:

 item = re.sub(r" ?\([^)]+\)", "", item) 

This corresponds to a wider range of characters than just \w .

In a regular expression, square brackets [...] denote a character class; character set for a single match. The class [ \(w+\)] means: matches a single character if it matches a set that includes a space, an opening bracket, all characters of the class \w , + plus or closing parentheses.

+8
source

All square brackets are taken regardless of the order in which you have characters, because [ ... ] is a character class. completely remove them:

 r" \(\w+\)" 

And would I add ? for extra space:

 r" ?\(\w+\)" 

demo version of regex101

+5
source

Source: https://habr.com/ru/post/957437/


All Articles