Python 正则表达式匹配VT100转义序列

2024-04-29 03:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个记录终端交互的Python程序(类似于脚本程序),我想在写入磁盘之前过滤掉VT100转义序列。我想使用这样的函数:

def strip_escapes(buf):
    escape_regex = re.compile(???) # <--- this is what I'm looking for
    return escape_regex.sub('', buf)

escape_regex中应该包含什么?在


Tags: 函数程序re脚本终端def记录磁盘
3条回答

VT100代码已经(主要)按照类似模式分组:

http://ascii-table.com/ansi-escape-sequences-vt-100.php

我认为最简单的方法是使用诸如regexbuddy这样的工具为每个VT100代码组定义一个regex。在

我找到了以下解决方案来成功解析vt100颜色代码并删除不可打印的转义序列。找到的代码段here在使用telnetlib运行telnet会话时成功删除了所有代码:

    def __processReadLine(self, line_p):
    '''
    remove non-printable characters from line <line_p>
    return a printable string.
    '''

    line, i, imax = '', 0, len(line_p)
    while i < imax:
        ac = ord(line_p[i])
        if (32<=ac<127) or ac in (9,10): # printable, \t, \n
            line += line_p[i]
        elif ac == 27:                   # remove coded sequences
            i += 1
            while i<imax and line_p[i].lower() not in 'abcdhsujkm':
                i += 1
        elif ac == 8 or (ac==13 and line and line[-1] == ' '): # backspace or EOL spacing
            if line:
                line = line[:-1]
        i += 1

    return line

转义序列的组合表达式可以是类似这样的通用表达式:

(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]

应与re.I一起使用

这包括:

  1. 两字节序列,即\x1b,后跟@_范围内的字符。在
  2. 一字节CSI,即\x9b,而不是\x1b + "["。在

但是,对于定义键映射或以引号括起来的字符串的序列,这将不起作用。在

相关问题 更多 >