Nick
Nick

Reputation: 387

Remove a character in string if it doesn't belong to a group of matching pattern in Python

If I have a string such that it contains many words. I want to remove the closing parenthesis if the word in the string doesn't start with _.

Examples input:

this is an example to _remove) brackets under certain) conditions.

Output:

this is an example to _remove) brackets under certain conditions.

How can I do that without splitting the words using re.sub?

Upvotes: 3

Views: 94

Answers (2)

Adam Smith
Adam Smith

Reputation: 54243

I wouldn't use regex here when a list comprehension can do it.

result = ' '.join([word.rstrip(")") if not word.startswith("_") else word
                   for word in words.split(" ")])

If you have possible input like:

someword))

that you want to turn into:

someword)

Then you'll have to do:

result = ' '.join([word[:-1] if word.endswith(")") and not word.startswith("_") else word
                  for word in words.split(" ")])

Upvotes: 2

timgeb
timgeb

Reputation: 78780

re.sub accepts a callable as the second parameter, which comes in handy here:

>>> import re
>>> s = 'this is an example to _remove) brackets under certain) conditions.'
>>> re.sub('(\w+)\)', lambda m: m.group(0) if m.group(0).startswith('_') else m.group(1), s)
'this is an example to _remove) brackets under certain conditions.'

Upvotes: 6

Related Questions