「Java」正規表現式で置換文字列にマッチグループを使うサンプル

2021年2月24日

書式
文字列.replaceAll(正規表現式、"$0,$1,xxx$n")
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.tm;
public class QikanMatchDemo {
public static final String strPtn = "([a-z]+)([0-9]+)";
public static final String tnA = "$0,$1";
public static final String tnB = "$0,$1,$2";
public static void main(String[] args) {
String strA = "test567#>";
String resA, resB;
resA = strA.replaceAll(strPtn, tnA);
System.out.println("結果1:\n" + resA);
resB = strA.replaceAll(strPtn, tnB);
System.out.println("結果2:\n" + resB);
}
}
package com.arkgame.study.tm; public class QikanMatchDemo { public static final String strPtn = "([a-z]+)([0-9]+)"; public static final String tnA = "$0,$1"; public static final String tnB = "$0,$1,$2"; public static void main(String[] args) { String strA = "test567#>"; String resA, resB; resA = strA.replaceAll(strPtn, tnA); System.out.println("結果1:\n" + resA); resB = strA.replaceAll(strPtn, tnB); System.out.println("結果2:\n" + resB); } }
package com.arkgame.study.tm;

public class QikanMatchDemo {

      public static final String strPtn = "([a-z]+)([0-9]+)";
      public static final String tnA = "$0,$1";
      public static final String tnB = "$0,$1,$2";

      public static void main(String[] args) {
            String strA = "test567#>";
            String resA, resB;
            resA = strA.replaceAll(strPtn, tnA);
            System.out.println("結果1:\n" + resA);
            resB = strA.replaceAll(strPtn, tnB);
            System.out.println("結果2:\n" + resB);
      }

}

実行結果
結果1:
test567,test#>
結果2:
test567,test,567#>

Windows10

Posted by arkgame