「Java」String.replaceFirst()で正規表現と一致する文字の最初部分を置換する方法

構文
public String replaceFirst(String regex, String replacement)
指定された正規表現に一致する、この文字列の最初の部分文字列に対し、指定された置換を実行します。
パラメータ:
regex – この文字列との一致を判定する正規表現
replacement – 最初に一致するものに置き換えられる文字列
Javaコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
public class MatchDemo {
protected static final String regexA = "[a-z]";
protected static final String regexB = "[A-Z]";
public static void main(String[] args) {
String strA = "test123";
String targetA = strA.replaceFirst(regexA, "*");
System.out.println(targetA);
System.out.println("********************************");
String strB = "TEST";
String targetB = strB.replaceFirst(regexB, "#");
System.out.println(targetB);
}
}
package com.arkgame.study; public class MatchDemo { protected static final String regexA = "[a-z]"; protected static final String regexB = "[A-Z]"; public static void main(String[] args) { String strA = "test123"; String targetA = strA.replaceFirst(regexA, "*"); System.out.println(targetA); System.out.println("********************************"); String strB = "TEST"; String targetB = strB.replaceFirst(regexB, "#"); System.out.println(targetB); } }
package com.arkgame.study;

public class MatchDemo {
      protected static final String regexA = "[a-z]";
      protected static final String regexB = "[A-Z]";

      public static void main(String[] args) {
            String strA = "test123";
            String targetA = strA.replaceFirst(regexA, "*");
            System.out.println(targetA);
            System.out.println("********************************");
            String strB = "TEST";
            String targetB = strB.replaceFirst(regexB, "#");
            System.out.println(targetB);

      }

}

実行結果
*est123
********************************
#EST

Java

Posted by arkgame