Skip to main content
 首页 » 编程设计

Python之从输出中删除包含列表中一个或多个子字符串的行

2024年11月01日37mfrbuaa

我想使用 python re 从输出中删除包含我的“pattern_list”中的子字符串之一的行,但将输出保留为一个字符串(没有这些行)。
所以,我查看了 re 库并编写了以下代码:

patterns_to_remove = ["$",":",">"] 
patterns = "|".join(patterns_to_remove) 
extra_lines_with_patterns = re.findall('\r\n.*{} \\w*'.format(re.escape(patterns)), str(output)) 
for extra_line in extra_lines_with_patterns: 
    output = str(output).replace(extra_line, "") 
return output 

所以如果我的输出是:

$a$ 
:b: 
^c^ 

我希望输出为:

a 
b 
c 

但最后我总是得到 None ,我想我在 re 标志上做错了。

请您参考如下方法:

您使用 re.escape(patterns) 转义了正则表达式模式的一部分,并且所有 | 运算符都变成了文字管道,\| .此外,您在通过 format 时没有将它们分组到模式中,并且模式看起来像 \r\n.*\$|\:|\>\w* ,所以它损坏了(参见 Why do ^ and $ not work as expected? )。

所以你需要

  • 使用 "|".join(map(re.escape, patterns_to_remove)) 转义 patterns_to_remove
  • 用 (?:...) 将 {} 括起来,non-capturing group ,即 '\r\n.*(?:{})\\w*'

使用

re.findall('\r\n.*(?:{}) \\w*'.format("|".join(map(re.escape, patterns_to_remove))), str(output)) 

或者,由于您要删除匹配项,只需使用 re.sub:

patterns_to_remove = ["$",":",">"] 
output = re.sub('\r\n.*(?:{}) \\w*'.format("|".join(map(re.escape, patterns_to_remove))), '', str(output)) 

注意:'\r\n.*(?:{})\\w*' = r'\r\n.*( ?:{})\w*'.