Python正则表达式以匹配VT100转义序列 [英] Python regex to match VT100 escape sequences
本文介绍了Python正则表达式以匹配VT100转义序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个记录终端交互的Python程序(类似于 script 程序),并且我想在写入磁盘之前过滤掉VT100转义序列.我想使用这样的功能:
I'm writing a Python program that logs terminal interaction (similar to the script program), and I'd like to filter out the VT100 escape sequences before writing to disk. I'd like to use a function like this:
def strip_escapes(buf):
escape_regex = re.compile(???) # <--- this is what I'm looking for
return escape_regex.sub('', buf)
escape_regex
中应该包含什么?
推荐答案
转义序列的组合表达式可以是这样的通用名称:
The combined expression for escape sequences can be something generic like this:
(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]
应与re.I
其中包括:
- 两个字节的序列,即
\x1b
,后跟@
到_
范围内的字符. - 一个字节的CSI,即
\x9b
而不是\x1b + "["
.
- Two-byte sequences, i.e.
\x1b
followed by a character in the range of@
until_
. - One-byte CSI, i.e.
\x9b
as opposed to\x1b + "["
.
但是,这不适用于定义键映射或包含在引号中的包含字符串的序列.
However, this will not work for sequences that define key mappings or otherwise included strings wrapped in quotes.
这篇关于Python正则表达式以匹配VT100转义序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文