使用
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'