Regex:提取字符串的一部分,消除它的特定模式



我有以下字符串示例,我只想提取它的中间部分,消除每个字符串前面和后面的模式:

Exp1:Error: -This can be an example. (YT-0E8)

Exp1:Warning: -Warning can happen too (WP-003)

Exp3:Error: Error can happen this way as well. (PP-W28)

我只想得到以下输出:

Ans1:-This can be an example.

Ans2:-Warning can happen too

Ans3:Error can happen this way as well.

正如你所看到的,我试图消除前面的第一模式,它可以是Error:Warning:,冒号后面有一个空格,第二模式是括号,前面有字母数字字符串和空格:(TT-T56)

我已经达到了这种程度来匹配前后图案,但无法找到完成它们的方法:^(Warning: |Error: ).*((w+-d+))$

有办法解决这个问题吗?

我会在这里使用正则表达式替换方法:

inp = ["Error: -This can be an example. (YT-0E8)", "Warning: -Warning can happen too (WP-003)", "Error: Error can happen this way as well. (PP-W28)"]
output = [re.sub(r'^w+:s*|s*(.*?)$', '', x) for x in inp]
print(output)
# ['-This can be an example.', '-Warning can happen too',
#  'Error can happen this way as well.']

这种方法可以去掉前面的标签后面的冒号或括号中的尾随项,留下您想要的内容。