Scala replaceFirst函数

Scala replaceFirst函数教程

Scala 中,replaceFirst 函数使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。

字符串正则替换

语法

String replaceFirst(String regex, String replacement)

参数

参数 描述
regex 正则表达式
replacement 需要替换为的字符串

返回值

返回替换后的字符串。

案例

字符串正则替换

使用 replaceFirst 函数,实现字符串正则替换

object HaiCoder { def main(args: Array[String]) : Unit = { println("嗨客网(www.haicoder.net)!\n") var str1 = "Hello,HaiCoder, Hello, World!" var str = str1.replaceFirst("Hello", "Hai") printf("str = %s\n", str) } }

程序运行后,控制台输出如下:

28_Scala replaceFirst函数.png

我们使用了 replaceFirst 函数实现了字符串的正则替换,这里,我们看到,只有第一个 “Hello” 被替换为了 “Hai”。

Scala replaceFirst函数总结

在 Scala 中,replaceFirst 函数使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。