ANSI エスケープシーケンスをIRC カラーシーケンスに変換したいと考えています。
そこで、正規表現 1 を書きましたが\e\[([\d;]+)?m
、shell_output_string.replaceFirst ("\\e\\[([\\d;]+)?m", "$1")
一致した部分文字列と残りの一致しない部分文字列の両方を返します。
次に、正規表現 2 を書きました。.*\e\[([\d;]+)?m.*
文字列全体に一致し、一致した部分文字列に置き換えることができることを願っていますが、replaceFirst (".*\\e\\[([\\d;]+)?m.*", "$1")
空の文字列を返しますがmatches (".*\\e\\[([\\d;]+)?m.*")
、true
. この正規表現の何が問題になっていますか?
次の質問は、次の質問と非常によく似ています: Pattern/Matcher group() to get substring in Java??
サンプルコード
import java.util.regex.*;
public class AnsiEscapeToIrcEscape
{
public static void main (String[] args)
{
//# grep --color=always bot /etc/passwd
//
//bot:x:1000:1000:bot:/home/bot:/bin/bash
byte[] shell_output_array = {
0x1B, 0x5B, 0x30, 0x31, 0x3B, 0x33, 0x31, 0x6D, 0x1B, 0x5B, 0x4B, // ^[[01;31m^[[K (#1 - #11)
0x62, 0x6F, 0x74, // bot (#12 - #14)
0x1B, 0x5B, 0x6D, 0x1B, 0x5B, 0x4B, // ^[[m^[[K (#15 - #20)
0x3A, 0x78, 0x3A, 0x31, 0x30, 0x30, 0x30, 0x3A, 0x31, 0x30, 0x30, 0x30, 0x3A, // :x:1000:1000: (#21 - #33)
0x1B, 0x5B, 0x30, 0x31, 0x3B, 0x33, 0x31, 0x6D, 0x1B, 0x5B, 0x4B, // ^[[01;31m^[[K (#34 - #44)
0x62, 0x6F, 0x74, // bot (#45 - #47)
0x1B, 0x5B, 0x6D, 0x1B, 0x5B, 0x4B, // ^[[m^[[K (#48 - #53)
0x3A, 0x2F, 0x68, 0x6F, 0x6D, 0x65, 0x2F, // :/home/ (#54 - #60)
0x1B, 0x5B, 0x30, 0x31, 0x3B, 0x33, 0x31, 0x6D, 0x1B, 0x5B, 0x4B, // ^[[01;31m^[[K (#61 - #71)
0x62, 0x6F, 0x74, // bot (#72 - #74)
0x1B, 0x5B, 0x6D, 0x1B, 0x5B, 0x4B, // ^[[m^[[K (#75 - #80)
0x3A, 0x2F, 0x62, 0x69, 0x6E, 0x2F, 0x62, 0x61, 0x73, 0x68, // :/bin/bash (#81 - #90)
};
String shell_output = new String (shell_output_array);
System.out.println (shell_output);
System.out.println ("total " + shell_output_array.length + " bytes");
final String CSI_REGEXP = "\\e\\[";
final String CSI_SGR_REGEXP_First = CSI_REGEXP + "([\\d;]+)?m";
final String CSI_SGR_REGEXP = ".*" + CSI_SGR_REGEXP_First + ".*";
System.out.println (shell_output.replaceFirst(CSI_SGR_REGEXP_First, "$1"));
System.out.println (shell_output.replaceFirst(CSI_SGR_REGEXP, "$1"));
}
}