Java如何计数替换字符串中第一次出现的子字符串?

在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.

猜你喜欢

转载自www.cnblogs.com/borter/p/9617156.html