代码之家  ›  专栏  ›  技术社区  ›  Leonardo

regex将控制台代码替换为空白

  •  0
  • Leonardo  · 技术社区  · 4 年前

    我正在为使用 console codes 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
    

    我用的是python3。

    谢谢!!

    1 回复  |  直到 4 年前
        1
  •  1
  •   Ryszard Czech    4 年前

    使用

    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'