Строка была возвращена из команды SSH, которую я выполнил. Я не могу использовать строку в ее текущем состоянии, потому что она содержит стандартные escape-последовательности ANSI. Как я могу программно удалить escape-последовательности, чтобы осталась только часть строки'examplefile.zip'.
Переведено автоматически
Ответ 1
Удалите их с помощью регулярного выражения:
import re
# 7-bit C1 ANSI sequences ansi_escape = re.compile(r''' \x1B # ESC (?: # 7-bit C1 Fe (except CSI) [@-Z\\-_] | # or [ for CSI, followed by a control sequence \[ [0-?]* # Parameter bytes [ -/]* # Intermediate bytes [@-~] # Final byte ) ''', re.VERBOSE) result = ansi_escape.sub('', sometext)
или, без флага VERBOSE, в сжатом виде:
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') result = ansi_escape.sub('', sometext)
Приведенное выше регулярное выражение охватывает все 7-битные escape-последовательности ANSI C1, но не открывающие 8-битные escape-последовательности C1. Последние никогда не используются в современном мире UTF-8, где один и тот же диапазон байтов имеет разное значение.
Если вам действительно нужно охватить и 8-битные коды (и затем, предположительно, вы работаете со bytes значениями), тогда регулярное выражение становится шаблоном байтов, подобным этому:
# 7-bit and 8-bit C1 ANSI sequences ansi_escape_8bit = re.compile(br''' (?: # either 7-bit C1, two bytes, ESC Fe (omitting CSI) \x1B [@-Z\\-_] | # or a single 8-bit byte Fe (omitting CSI) [\x80-\x9A\x9C-\x9F] | # or CSI + control codes (?: # 7-bit CSI, ESC [ \x1B\[ | # 8-bit CSI, 9B \x9B ) [0-?]* # Parameter bytes [ -/]* # Intermediate bytes [@-~] # Final byte ) ''', re.VERBOSE) result = ansi_escape_8bit.sub(b'', somebytesvalue)
которые можно сократить до
# 7-bit and 8-bit C1 ANSI sequences ansi_escape_8bit = re.compile( br'(?:\x1B[@-Z\\-_]|[\x80-\x9A\x9C-\x9F]|(?:\x1B\[|\x9B)[0-?]*[ -/]*[@-~])' ) result = ansi_escape_8bit.sub(b'', somebytesvalue)
Приведенный вами пример содержит 4 кода CSI (Control Sequence Introducer), обозначенных открывающими байтами \x1B[ или ESC [, и каждый содержит код SGR (Select Graphic Rendition), потому что каждый из них заканчивается на m. Параметры (разделенные ; точкой с запятой) между ними сообщают вашему терминалу, какие атрибуты графического отображения использовать. Итак, для каждой \x1B[....m последовательности используются 3 кода::
0 (или 00 в этом примере): сбросить, отключить все атрибуты
1 (или 01 в примере): выделено жирным шрифтом
31: red (foreground)
However, there is more to ANSI than just CSI SGR codes. With CSI alone you can also control the cursor, clear lines or the whole display, or scroll (provided the terminal supports this of course). And beyond CSI, there are codes to select alternative fonts (SS2 and SS3), to send 'private messages' (think passwords), to communicate with the terminal (DCS), the OS (OSC), or the application itself (APC, a way for applications to piggy-back custom control codes on to the communication stream), and further codes to help define strings (SOS, Start of String, ST String Terminator) or to reset everything back to a base state (RIS). The above regexes cover all of these.
Note that the above regex only removes the ANSI C1 codes, however, and not any additional data that those codes may be marking up (such as the strings sent between an OSC opener and the terminating ST code). Removing those would require additional work outside the scope of this answer.
Ответ 2
The accepted answer only takes into account ANSI Standardized escape sequences that are formatted to alter foreground colors & text style. Many sequences do not end in 'm', such as: cursor positioning, erasing, and scroll regions. The pattern bellow attempts to cover all cases beyond setting foreground color and text-style.
Below is the regular expression for ANSI standardized control sequences: