Home > Net >  Python regex matching characters before and inside (): ex _(some_text)
Python regex matching characters before and inside (): ex _(some_text)

Time:05-12

This regex expression has proved to be quite the challenge. Essentially I want to be able to remove any number of text between parentheses, including the character before the ().

expected input: 'some_(text)'
expected output: 'some'

What I have tried:

import re
s = 'some_(text)'
s = re.sub(r"\([^()]*\)", "", s)

outputs: 'some_'

... For the life of me I can't get rid of the underscore. I am very time pressured and really appreciate any help.

Thank you! Hopefully this will help someone else as well

CodePudding user response:

Prepend by _?:

>>> re.sub(r"_?\([^()]*\)", "", s)
'some'

CodePudding user response:

You can try this code:

a = re.sub(r"[^a-zA-Z]*\([^()]*\)","",s)

  • [^a-z]: Not matches any characters except those in the range a-z and A-Z
  • "*": zero and more character
  • Related