4
\$\begingroup\$

Im trying to extract the text on the left, outside the parenthesis ():

import re
clean_title = re.match(r'(.*)\(.*\)', title.lower()) 
if clean_title:
   return clean_title.group(1).rstrip()

Any suggestions to improve it, maybe without regex?

Expected results:

>>'Alone in the Dark (The Cincinnati Series Book 2)'
>>'alone in the dark'
\$\endgroup\$
  • 3
    \$\begingroup\$ How certain are you that the parentheses will either occur in a pair at the end of the title, or not at all? Is there any chance of nested parentheses? How should it behave in such unexpected situations? \$\endgroup\$ – 200_success Aug 18 '17 at 6:23
5
\$\begingroup\$

You can use split() to split the whole text based on the first occurrence of the ( character. This will return a list, pick the first element of the list:

>>> text = 'Alone in the Dark (The Cincinnati Series Book 2)'
>>> text.split('(')[0]
'Alone in the Dark '
>>> 
\$\endgroup\$
7
\$\begingroup\$

Assuming the text on the left cannot contain opening parenthesis, splitting by the first opening parenthesis might work as well:

>>> clean_title = 'Alone in the Dark (The Cincinnati Series Book 2)'
>>> clean_title.split('(', 1)[0].lower().rstrip()
'alone in the dark'

Note that it will not fail even if there are no parenthesis:

>>> clean_title = 'Test'
>>> clean_title.split('(', 1)[0].lower().rstrip()
'test'

As far as the regular expression approach, you might also use re.sub() which would not require checking if there is a match or not. And, as a bonus, let's account for the extra space before the parenthesis:

>>> re.sub(r"(.*?)\s?\(.*?\)", r"\1", clean_title).lower()
'alone in the dark'

Or:

>>> re.sub(r"\s?\(.*?\)", r"", clean_title).lower()
'alone in the dark'

You can also do the lowering part in a replacement function:

>>> re.sub(r"(.*?)\s?\(.*?\)", lambda m: m.group(1).lower(), clean_title)
'alone in the dark'

Also note that I'm using non-greedy regular expressions.

\$\endgroup\$
  • 1
    \$\begingroup\$ r"(.*?)\s?\(.*?\)", r"\1" seems overkill if not using the lambda - r"\s*\(.*\)", "" (replacing with nothing) should be enough, right? \$\endgroup\$ – muru Aug 18 '17 at 6:37
  • \$\begingroup\$ @muru good point, included into the answer, thanks! \$\endgroup\$ – alecxe Aug 18 '17 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.