57

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

enter image description here

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

5
  • Java or JavaScript ? Commented Jun 20, 2018 at 10:29
  • @HalayemAnis Java Commented Jun 20, 2018 at 10:29
  • @HalayemAnis it's Kotlin. Kotlin is a JVM language, which means it uses Java API's (the reason it's tagged Java) Commented Jun 20, 2018 at 10:29
  • 2
    @daka That's a kotlin String, not a java String. Kotlin has just replace Commented Jun 20, 2018 at 10:30
  • 1
    The Kotlin replace function can accept a Regex argument. It doesn't need replaceAll. Commented Jun 20, 2018 at 10:31

3 Answers 3

83

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"
Sign up to request clarification or add additional context in comments.

1 Comment

What do I do if I replace with $1 like here? stackoverflow.com/a/40487511/2111778
20

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");

Comments

6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.