【问题标题】:regex to replace console code with whitespaces正则表达式用空格替换控制台代码
【发布时间】:2021-05-18 19:42:16
【问题描述】:

我正在为使用 console codes 的控制台应用程序编写一些 Python 测试,但在优雅地处理 ESC H 序列时遇到了一些问题。

我有s = r'\x1b[12;5H\nSomething' 输入字符串,我想用 Something 替换它。我正在尝试使用以下正则表达式:

re.sub(r'\x1b\[([0-9,A-Z]{1,2};([0-9]{1,2})H)', r'\2', s)

当然会创建5Something。

我想要的是某种效果

re.sub(r'\x1b\[([0-9,A-Z]{1,2};([0-9]{1,2})H)', ' '*(int(r'\2')-1), s)

即创建比第二个捕获组的空格数少一个。

如果有一种方法可以简单地将我使用 print(s) 时得到的内容呈现在一个字符串中,我也会非常高兴:

    Something

我正在使用 Python 3。

非常感谢!!

【问题讨论】:

    标签: python regex console-application vt100


    【解决方案1】:

    使用

    import re
    s = r'\x1b[12;5H\nSomething'
    pattern = r'\\x1b\[[0-9A-Z]{1,2};([0-9]{1,2})H\\n'
    print(re.sub(pattern, lambda x: ' '*(int(x.group(1))-1), s))
    

    见Python proof。见regex proof。

    解释

    --------------------------------------------------------------------------------
      \\                       '\'
    --------------------------------------------------------------------------------
      x1b                      'x1b'
    --------------------------------------------------------------------------------
      \[                       '['
    --------------------------------------------------------------------------------
      [0-9A-Z]{1,2}            any character of: '0' to '9', 'A' to 'Z'
                               (between 1 and 2 times (matching the most
                               amount possible))
    --------------------------------------------------------------------------------
      ;                        ';'
    --------------------------------------------------------------------------------
      (                        group and capture to \1:
    --------------------------------------------------------------------------------
        [0-9]{1,2}               any character of: '0' to '9' (between 1
                                 and 2 times (matching the most amount
                                 possible))
    --------------------------------------------------------------------------------
      )                        end of \1
    --------------------------------------------------------------------------------
      H                        'H'
    --------------------------------------------------------------------------------
      \\                       '\'
    --------------------------------------------------------------------------------
      n                        'n'
    

    【讨论】:

      猜你喜欢
      • 2015-01-19
      • 1970-01-01
      • 2015-09-16
      • 2020-09-12
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      相关资源
      最近更新 更多