Java String class replaceAll method missing

ぃ、小莉子 提交于 2020-12-30 04:49:27

问题


I'm having a very weird issue right now, the replaceAll method is missing from the String object.

JDK version: 1.8.0
Android Studio version: 3.1.3
Kotlin version: 1.2

It hasn't been removed, so whats going on here??


回答1:


You can do this with just replace in Kotlin:

"foo and foo".replace("foo", "bar") // "bar and bar"

Note that the call above replaces the literal strings, if you need a Regex as the first parameter you can do either of the following:

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



回答2:


Kotlin has it's own String class. All the replace methods are just replace.

replaceAll in Java uses regex, so I assume your goal is using regex. To do this, just use a regex object when you pass to replace:

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

If you don't have regex (and that's wrong), don't call .toRegex():

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



回答3:


Kotlin has replaceAll as replace:

replace in Kotlin

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

Returns a new string with all occurrences of oldChar replaced with newChar.



来源:https://stackoverflow.com/questions/50946008/java-string-class-replaceall-method-missing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!