Home > Back-end >  Using regex, how to remove a substring which occures multiple times?
Using regex, how to remove a substring which occures multiple times?

Time:09-05

The string which i have is this: (enter down), (enter up), (o down), (k down), (o up), (a down), (a up), (k up), (y down),.

How would I, in this string remove only the parenthesis which have the keyword down in them (by remove i mean replace with nothing, basically with "").

The result which I want to get: , (enter up), , , (o up), , (a up), (k up), ,.

Its ugly but I need it like this.

CodePudding user response:

I think this is answered elsewhere, but you can definitely use re.sub. An example:

>>> from re import sub
>>> x = '(enter down), (enter up), (o down), (k down), (o up), (a down), (a up), (k up), (y down),'
>>> sub(r'\(\w \s?down\)', '', x)
', (enter up), , , (o up), , (a up), (k up), ,'
>>> 
  • Related