Java的String类replaceAll方法缺失

50

我现在遇到了一个非常奇怪的问题,replaceAll方法在String对象中找不到。

JDK版本:1.8.0
Android Studio版本:3.1.3
Kotlin版本:1.2

进入图片描述

它没有被删除,那么这里发生了什么??


Java还是JavaScript? - Halayem Anis
@HalayemAnis Java - olfek
@HalayemAnis 这是 Kotlin。Kotlin 是一种 JVM 语言,这意味着它使用 Java API(这就是为什么它被标记为 Java 的原因)。 - Zoe stands with Ukraine
2
@daka 这是 Kotlin 的 String,不是 Java 的 String。Kotlin 只有 replace - Federico klez Culloca
1
Kotlin的replace函数可以接受一个Regex参数,不需要使用replaceAll - khelwood
3个回答

77
你可以仅使用 Kotlin 中的 replace 来完成此操作。
"foo and foo".replace("foo", "bar") // "bar and bar"

请注意,上述调用将替换字面字符串,如果您需要将Regex作为第一个参数,则可以执行以下任一操作:


"foo and bar".replace("[abcd]".toRegex(), "x") // "foo xnx xxr"
"foo and bar".replace(Regex("[abcd]"), "x")    // "foo xnx xxr"

1
如果我像这样替换为$1,该怎么办?https://dev59.com/eHA75IYBdhLWcg3wGlEa#40487511 - xjcl

19

Kotlin有自己的String类。所有的替换方法都只是使用replace

Java中的replaceAll使用正则表达式,因此我假设您想要使用正则表达式。为了实现这一点,当您传递给replace时,只需使用一个正则表达式对象即可:

sb.toString().replace("your regex".toRegex(), "replacement");

如果你没有正则表达式(这是不正确的),就不要调用.toRegex()

sb.toString().replace("replace target", "replacement");

6

Kotlin中的replaceAll被替换为replace:

在Kotlin中使用replace

actual fun String.replace(
oldChar: Char, 
newChar: Char, 
ignoreCase: Boolean = false
): String (source)

返回一个新的字符串,其中所有旧字符的出现都被替换为新字符。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接