Java replaceFirst() 方法

Java replaceFirst() 方法

Java String类


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 youj,I am from youj。");

		System.out.print("返回值 :" );
		System.out.println(Str.replaceFirst("youj",
		                         "google" ));
		System.out.print("返回值 :" );
		System.out.println(Str.replaceFirst("(.*)youj(.*)",
		                         "google" ));
	}
}

以上程序执行结果为:

匹配成功返回值 :youj
匹配失败返回值 :www.google.com

Java String类

版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《Java replaceFirst() 方法》
文章链接:https://zhuji.vsping.com/295075.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。