Java String replaceFirst() 方法
示例
用不同的子字串替換正則表示式的第一個匹配項
String myStr = "This is W3Schools";
String regex = "is";
System.out.println(myStr.replaceFirst(regex, "at"));
定義和用法
replaceFirst()
方法用新的子字串替換字串中正則表示式的第一個匹配項。
替換字串可能包含 `$n` 形式的反向引用,其中 `n` 是模式中組的索引。在返回的字串中,`$n` 例項將被組匹配的子字串替換,如果使用 `$0`,則會被整個表示式替換。有關使用反向引用的示例,請參閱下面的“更多示例”。
提示: 請參閱 Java 正則表示式 教程來學習正則表示式。
語法
public String replaceFirst(String regex, String replacement)
引數值
引數 | 描述 |
---|---|
regex | 必填。定義要搜尋的子字串的正則表示式。 |
replacement | 必填。將替換第一個匹配項的子字串。 |
技術詳情
返回 | 字串的副本,其中第一個匹配正則表示式的子字串被新的子字串替換。 |
---|---|
丟擲 | PatternSyntaxException - 如果正則表示式的語法不正確。 |
Java 版本 | 1.4 |
更多示例
示例
使用反向引用將第一個數字括在括號中
String myStr = "Quest complete! Earned 30 gold and 500 experience.";
String regex = "[0-9]+";
System.out.println(myStr.replaceFirst(regex, "($0)"));
❮ String Methods