Skip to main content
 首页 » 编程设计

python之用于从文本中分离 ANSI 转义字符的正则表达式

2024年10月17日30zfyouxi

我使用 colorama 将 ANSI 代码添加到文本中,我需要从文本中分离出 ANSI 颜色代码,以便可以按列格式打印文本。以下表达式将单色代码与文本分隔开,但不分隔双色代码。

# adapted from https://stackoverflow.com/questions/2186919 
split_ANSI_escape_sequences = re.compile(r""" 
    (?P<col> 
    \x1b     # literal ESC 
    \[       # literal [ 
    [;\d]*   # zero or more digits or semicolons 
    [A-Za-z] # a letter 
    )* 
    (?P<text>.*) 
    """, re.VERBOSE).fullmatch 
 
def split_ANSI(s): 
    return split_ANSI_escape_sequences(s).groupdict() 

这是结果:

>>> split_ANSI('\x1b[31m\x1b[1mtext') 
{'col': '\x1b[1m', 'text': 'text'} 

它正确拆分,但丢失了格式信息。我期待着

{'col': '\x1b[31m\x1b[1m', 'text': 'text'} 

作为结果。

如何获取第一组中所有可能的转义序列?

请您参考如下方法:

我在 Python RegEx multiple groups 找到了答案以不同的方式提问。

第一个命名的组会被每个匹配项覆盖。这个版本有效:

split_ANSI_escape_sequences = re.compile(r""" 
    (?P<col>(\x1b     # literal ESC 
    \[       # literal [ 
    [;\d]*   # zero or more digits or semicolons 
    [A-Za-z] # a letter 
    )*) 
    (?P<name>.*) 
    """, re.VERBOSE).match 
 
def split_ANSI(s): 
    return split_ANSI_escape_sequences(s).groupdict()