Java 正規表現にマッチした最初の文字列を変換するサンプル

環境
Windows11 pro 64bit
java 19.0.1

構文
文字列.replaceFirst​(“正規表現",置換する文字列)
正規表現にマッチした最初の文字列を変換するには、「replaceFirst​」を利用します

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
String str1 = "0123456";
String str2 = "b123456";
String str3 = "b";
String regex = "[0-9]";
System.out.println(str1.replaceFirst(regex,"A"));
System.out.println(str2.replaceFirst(regex,"A"));
System.out.println(str3.replaceFirst(regex,"A"));
}
}
import java.util.*; public class Main { public static void main(String[] args) throws Exception { String str1 = "0123456"; String str2 = "b123456"; String str3 = "b"; String regex = "[0-9]"; System.out.println(str1.replaceFirst(regex,"A")); System.out.println(str2.replaceFirst(regex,"A")); System.out.println(str3.replaceFirst(regex,"A")); } }
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        String str1 = "0123456";
        String str2 = "b123456";
        String str3 = "b";
        String regex = "[0-9]";

        System.out.println(str1.replaceFirst(regex,"A")); 
        System.out.println(str2.replaceFirst(regex,"A")); 
        System.out.println(str3.replaceFirst(regex,"A"));  
    }
}

実行結果
A123456
bA23456
b

IT

Posted by arkgame