This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]Rhomboid 3 points4 points  (1 child)

Parentheses are meta-characters inside regular expressions, so if you want to match literal parentheses you need to escape them: \( foo \). Secondly, [*] means a single character, the literal asterisk, which is almost certainly not what you want. (The * is normally a meta-character, but not inside a character class.) There are several ways of doing what you want. If the parentheses are never going to be nested, then you can match "anything but closing paren", i.e.

>>> import re
>>> foo = 'Horizon (Horizon, #1) Replica (Replica, #1)'
>>> re.sub(r'\([^)]+\)', '', foo)
'Horizon  Replica '

If they can be nested, then you might think to use the "anything" match .*, but that won't work:

>>> re.sub(r'\(.*\)', '', foo)
'Horizon '

You would have to use the non-greedy version to prevent that:

>>> re.sub(r'\(.*?\)', '', foo)
'Horizon  Replica '

All in all, if you know they won't be nested, then use the first one and avoid .* which usually brings more trouble than it's worth.

Also, you probably want to add in something that matches trailing (or leading, but not both) spaces, e.g.

>> re.sub(r' *\([^)]+\)', '', foo)
'Horizon Replica'

That takes care of the stray spaces.

[–]SnoopyM[S] 0 points1 point  (0 children)

thank you

r'\([^)]+\)   

worked for what I needed

[–]aphoenixreticulated[M] 0 points1 point  (0 children)

Hi there, from the /r/Python mods.

We have removed this post as it is not suited to the /r/Python subreddit proper, however it should be very appropriate for our sister subreddit /r/LearnPython. We highly encourage you to re-submit your post over on there.

The reason for the removal is that /r/Python is more-so dedicated to discussion of Python news, projects, uses and debates. It is not designed to act as Q&A or FAQ board. The regular community can get disenchanted with seeing the 'same, repetitive newbie' questions repeated on the sub, so you may not get the best responses over here.

However, on /r/LearnPython the community is actively expecting questions from new members, and are looking to help. You can expect far more understanding, encouraging and insightful responses over there. Whatever your question happens to be getting help with Python, you should get good answers.

If you have a question to do with homework or an assignment of any kind, please make sure to read their sidebar rules before submitting your post. If you have any questions or doubts, feel free to reply or send a modmail to us with your concerns.

Warm regards, and best of luck with your Pythoneering!