Java replaceFirst() 方法
replaceFirst() 方法使用給定的參數replacement 替換字符串第一個匹配給定的正則表達式的子字符串。
語法
public String replaceFirst(String regex, String replacement)
參數
regex --匹配此字符串的正則表達式。
replacement --用來替換第一個匹配項的字符串。
返回值
成功則返回替換的字符串,失敗則返回原始字符串。
實例
public class Test { public static void main(String args[]) { String Str = new String("hello w3big,I am from w3big。"); System.out.print("返回值 :" ); System.out.println(Str.replaceFirst("w3big", "google" )); System.out.print("返回值 :" ); System.out.println(Str.replaceFirst("(.*)w3big(.*)", "google" )); } }
以上程序執行結果為:
匹配成功返回值 :w3big 匹配失败返回值 :www.google.com