【问题标题】:Python regex to match VT100 escape sequencesPython 正则表达式匹配 VT100 转义序列
【发布时间】:2011-12-13 00:41:43
【问题描述】:

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

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

escape_regex 应该写什么?

【问题讨论】:

标签: python regex vt100


【解决方案1】:

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

    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

【讨论】:

【解决方案2】:

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

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

应该和re.I一起使用

这包含:

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

但是,这不适用于定义键映射或以其他方式包含用引号括起来的字符串的序列。

【讨论】:

    【解决方案3】:

    VT100 代码已经按照类似的模式进行了分组(大部分):

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

    我认为最简单的方法是使用 regexbuddy 之类的工具为每个 VT100 代码组定义一个正则表达式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 2013-09-22
      • 2011-12-03
      • 2012-04-23
      相关资源
      最近更新 更多