如何从Python字符串中删除括号内的文本?

CPU*_*CPU -1 python regex python-3.x

我试图删除括号和这些括号中的文本,以及连字符.一些字符串示例如下所示:
example = 'Year 1.2 Q4.1 (Section 1.5 Report (#222))'
example2 = 'Year 2-7 Q4.8 - Data markets and phases' ##there are two hyphens

我希望结果如下:

example = 'Year 1.2 Q4.1'  
example2 = 'Year 2-7 Q4.8'  
Run Code Online (Sandbox Code Playgroud)

如何删除位于括号和特殊字符内或之后的文本?我只能找到str.strip()方法.我是Python新手,所以非常感谢任何反馈!

Moi*_*dri 5

您可以使用以下正则表达式来获得所需的结果:

"\(.*\)|\s-\s.*"
#   ^     ^  Pattern 2: everything followed by space, '-' hyphen, space
#   ^   Pattern 1: everything within brackets (....)
Run Code Online (Sandbox Code Playgroud)

样品运行:

>>> import re
>>> my_regex = "\(.*\)|\s-\s.*"

>>> example = 'Year 1.2 Q4.1 (Section 1.5 Report (#222))'
>>> example2 = 'Year 2-7 Q4.8 - Data markets and phases'

>>> re.sub(my_regex, "", example)
'Year 1.2 Q4.1'
>>> re.sub(my_regex, "", example2)
'Year 2-7 Q4.8'
Run Code Online (Sandbox Code Playgroud)

在这里,我正在使用re.sub(pattern, repl, string, ...)哪个文件说:

返回通过替换repl替换字符串中最左边的非重叠模式而获得的字符串.如果未找到模式,则返回字符串不变.repl可以是字符串或函数; 如果它是一个字符串,则处理其中的任何反斜杠转义.