删除 Python 中的 ANSI 转义序列

问题描述 投票:0回答:0

我正在尝试从字符串中删除 ANSI 转义序列。

我已经尝试了this post中提出的所有解决方案,但没有一个有效,因此我得出结论,我的情况有点不同。

我有以下代码应该替换所有 ANSI 转义序列:

print("ascii: " + ascii(string))
x = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])').sub('', string)
y = re.compile(br'(?:\x1B[@-Z\\-_]|[\x80-\x9A\x9C-\x9F]|(?:\x1B\[|\x9B)[0-?]*[ -/]*[@-~])').sub(b'', string.encode("utf-8"))
print("not escaped X: " + ascii(x))
print("not escaped Y: " + ascii(y))

然而,我得到以下输出:

ascii: '\x1b[m>....\x1b[?1h\x1b=\x1b[?2004h>....\r\x1b[K\x1b[32m[03:33:57] blabla'
not escaped X: '>....\x1b=>....\r[03:33:57] blabla'
not escaped Y: b'>....\x1b=>....\r[03:33:57] blabla'

如何替换所有 ANSI 转义序列,以便预期结果为:

[03:33:57] blabla

python regex escaping ansi-escape ansi
© www.soinside.com 2019 - 2024. All rights reserved.