我现在遇到了一个非常奇怪的问题,replaceAll
方法在String
对象中找不到。
JDK版本:1.8.0
Android Studio版本:3.1.3
Kotlin版本:1.2
它没有被删除,那么这里发生了什么??
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
,该怎么办?https://dev59.com/eHA75IYBdhLWcg3wGlEa#40487511 - xjclKotlin有自己的String类。所有的替换方法都只是使用replace
。
Java中的replaceAll
使用正则表达式,因此我假设您想要使用正则表达式。为了实现这一点,当您传递给replace
时,只需使用一个正则表达式对象即可:
sb.toString().replace("your regex".toRegex(), "replacement");
如果你没有正则表达式(这是不正确的),就不要调用.toRegex()
:
sb.toString().replace("replace target", "replacement");
Kotlin中的replaceAll被替换为replace:
actual fun String.replace(
oldChar: Char,
newChar: Char,
ignoreCase: Boolean = false
): String (source)
String
,不是 Java 的String
。Kotlin 只有replace
。 - Federico klez Cullocareplace
函数可以接受一个Regex
参数,不需要使用replaceAll
。 - khelwood