Java matcherメソッドで正規表現にマッチした最初の文字列を置換する

環境
Java 17
Windows 11 Pro 64bit

構文
Pattern p = Pattern.compile(“対象文字列");
Matcher mt = p.matcher(“対象文字列");
mt.replaceFirst(“置換する文字列");
正規表現にマッチした最初の文字列を置換するには、「Pattern.compile」と「replaceFirst」を使用します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import java.util.regex.*;
public class App {
public static void main(String[] args) throws Exception {
String reg = "[0-9]{3}"; // 3文字の2から9の半角数字
Pattern p = Pattern.compile(reg);
Matcher ma = p.matcher("12398");
System.out.println(ma.replaceFirst("56"));
Matcher mb = p.matcher("abcft333abcft");
System.out.println(mb.replaceFirst("abcft"));
}
}
import java.util.regex.*; public class App { public static void main(String[] args) throws Exception { String reg = "[0-9]{3}"; // 3文字の2から9の半角数字 Pattern p = Pattern.compile(reg); Matcher ma = p.matcher("12398"); System.out.println(ma.replaceFirst("56")); Matcher mb = p.matcher("abcft333abcft"); System.out.println(mb.replaceFirst("abcft")); } }
import java.util.regex.*;

public class App {
    public static void main(String[] args) throws Exception {

        String reg = "[0-9]{3}"; // 3文字の2から9の半角数字

        Pattern p = Pattern.compile(reg);

        Matcher ma = p.matcher("12398");

        System.out.println(ma.replaceFirst("56"));

        Matcher mb = p.matcher("abcft333abcft");

        System.out.println(mb.replaceFirst("abcft"));

    }
}

実行
5698
abcftabcftabcft

IT

Posted by arkgame