Java如何計數替換字符串中第一次出現的子字符串?
阿新 • • 發佈:2018-09-10
aci 代碼示例 compile pac instr span int com pla
在Java編程中,如何拆分正則表達式和字符串?
以下示例演示如何使用Matcher
類的replaceFirst()
方法替換字符中指定的子字符串的首次出現。
package com.yiibai;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceFirstOccurrence {
public static void main(String args[]) {
Pattern p = Pattern.compile("hello");
String instring = "hello, hello word.";
System.out.println("initial String: " + instring);
Matcher m = p.matcher(instring);
String tmp = m.replaceFirst("Java");
System.out.println("String after replacing 1st Match: " + tmp);
}
}
Java
上述代碼示例將產生以下結果 -
initial String: hello, hello word.
String after replacing 1st Match: Java, hello word.
Java如何計數替換字符串中第一次出現的子字符串?