Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-从输出中删除包含列表中一个或多个子字符串的行_Python_Regex - Fatal编程技术网

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

Python-从输出中删除包含列表中一个或多个子字符串的行,python,regex,Python,Regex,我想用python re从包含“模式列表”中的一个子字符串的输出中删除行,但将输出保留为一个字符串(没有这些行)。 因此,我查看了re库并编写了以下代码: patterns_to_remove = ["$",":",">"] patterns = "|".join(patterns_to_remove) extra_lines_with_patterns = re.findall('\r\n.*{} \\w*'.format(re.escape(patterns)), str(output

我想用python re从包含“模式列表”中的一个子字符串的输出中删除行,但将输出保留为一个字符串(没有这些行)。
因此,我查看了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

但是我最终总是没有得到任何结果,我想我对re标志做了一些错误。

您使用
re.escape(patterns)
对regex模式的一部分进行了转义,所有
操作符都变成了文字管道,
\
。此外,在通过
格式
时,您没有将它们分组到模式中,模式看起来像
\r\n.\$\124;\:\ 124;\>\ w*
,因此它已损坏(请参阅)

所以你需要

  • 使用
    “|”将
    模式转义到_移除
    。加入(映射(重新转义,模式_到_移除))
  • (?:…)
    {}
    括起来,即
    '\r\n.*(:{})\\w*'
使用

或者,由于要删除匹配项,只需使用
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*'
您没有正确地转义模式和粘贴替换,请使用
re.findall('\r\n.*({})\\w*'.format(“|“.join(map(re.escape,patterns\u-to-remove))),str(output))
实际上,您不需要
findall,,如果使用正则表达式进行删除,出于好奇,请使用
re.sub
:为什么不使用类似
print(''.join([x代表x,如果x不在“$:^”]))的LC呢?
patterns_to_remove = ["$",":",">"]
output = re.sub('\r\n.*(?:{}) \\w*'.format("|".join(map(re.escape, patterns_to_remove))), '', str(output))