Delphi XE3 - 从字符串中删除 Ansi 代码/颜色

Delphi XE3 - Remove Ansi Code / Color from string

我正在努力处理 Ansi 代码字符串。我得到 [32m, [37m, [K 等字符。

有没有更快的方法eliminate/strip 从我得到的字符串中提取 ansi 代码,而不是通过字符循环搜索 ansi 代码的起点和终点?

我知道声明是这样的:#27'['#x';'#y';'#z'm'; 其中 x、y、z... 是 ANSI 代码。所以我假设我应该搜索 #27 直到找到 "m;"

有没有现成的功能可以实现我想要的功能?除了 this 篇文章外,我的搜索没有返回任何内容。 谢谢

您可以使用如下代码(最简单的有限状态机)非常快速地处理此协议:

var
  s: AnsiString;
  i: integer;
  InColorCode: Boolean;
begin
  s := 'test'#27'['#5';'#30';'#47'm colored text';

  InColorCode := False;

  for i := 1 to Length(s) do
    if InColorCode then
      case s[i] of
          #0: TextAttrib = Normal;
          ...
          #47: TextBG := White;
          'm': InColorCode := false;
        else;
         // I do nothing here for `;`, '[' and other chars.
         // treat them if necessary

      end;
     else
       if s[i] = #27 then
         InColorCode := True
       else
         output char with current attributes

正在从 ESC 代码中清除字符串:

procedure StripEscCode(var s: AnsiString);
const
  StartChar: AnsiChar = #27;
  EndChar: AnsiChar = 'm';
var
  i, cnt: integer;
  InEsc: Boolean;
begin
  Cnt := 0;
  InEsc := False;
  for i := 1 to Length(s) do
    if InEsc then begin
      InEsc := s[i] <> EndChar;
      Inc(cnt)
    end
    else begin
      InEsc := s[i] = StartChar;
      if InEsc then
        Inc(cnt)
      else
      s[i - cnt] :=s[i];
    end;
  setLength(s, Length(s) - cnt);
end;