python中使用正则表达式转义颜色字符串

2024-09-30 19:35:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试转义这个序列中的字符串

[0m[ERROR] [1585551547.349979]: Failed to create bragfiles/downtimer/fight100/2020-03-27. Error: 550 Create directory operation failed.
[ERROR] [1585551547.349979]: Failed to create bragfiles/downtimer/fight100/2020-03-27. Error: 550 Create directory operation failed.

[32m[INFO] [2020-03-29 23:58:50.607198] TaskManager.poll: system has no current task.[0m
[INFO] [2020-03-29 23:58:50.607198] TaskManager.poll: system has no current task.

再加上偶尔的双重符号

"[0m[32m[INFO] [2020-03-29 23:58:34.695268] Polling for updates from the server for fight100...[0m"
"[INFO] [2020-03-29 23:58:34.695268] Polling for updates from the server for fight100..."

我以前遇到过这种情况,但在我的情况下似乎不正确:

  1. How can I remove the ANSI escape sequences from a string in python
  2. Remove all ANSI colors/styles from strings

我一直在尝试各种各样的\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])变体,但我认为这不合适

但到目前为止,我尝试过的正则表达式似乎都不够通用


Tags: thetofrominfoforcreateerroroperation
1条回答
网友
1楼 · 发布于 2024-09-30 19:35:04

(一个或两个(颜色转义序列))后跟(方括号内的大写字母字符)(正向前瞻)

pat = r'''((\[\d+m){1,2})(?=\[[A-Z]+\])'''

使用此字符串:

s = '''[0m[ERROR] [1585551547.349979]: xyz xyz.
[0m[32m[INFO] [2020-03-29 23:58:34.695268] hjk hjk.[0m[32m[INFO] [2020-03-29 23:58:34.695268] foo bar foo'''

正向前瞻可防止捕获最后一位


>>> print(re.sub(pat,'',s))
[ERROR] [1585551547.349979]: xyz xyz.
[INFO] [2020-03-29 23:58:34.695268] hjk hjk.[INFO] [2020-03-29 23:58:34.695268] foo bar foo
>>>

如果需要删除指定前景和背景色的序列,如

[2m[93m[0m[32m[INFO] [2020-03-29 23:58:34.695268] foo bar foo

pat = r'''((\[\d+m){1,})(?=\[[A-Z]+\])'''用于(一个或多个)而不是(一个或两个)


如果有这样的东西

[0m[1;37m[ERROR] [1585551547.349979]: xyz xyz.
[0m[1;37m[0;32m[ERROR] [1585551547.349979]: xyz xyz.

使用pat = r'''(\[([01];)?\d+m){1,}(?=\[[A-Z]+\])'''


您的一些示例字符串在字符串的中间显示了颜色序列,您所需的输出显示它们被替换-与您的注释相反

all color codes in the beginning of lines.

这些模式将从字符串中间删除序列

相关问题 更多 >