Reputation: 1681
I have a string and expect it to be changed when calling replaceFirst
but it always is the same, not changed.
"there are 400 pictures".replaceFirst(" [0-9]{3}", " a lot of ")
How can it be fixed?
Upvotes: 2
Views: 600
Reputation: 273540
You are calling the overload of replaceFirst
that takes a String
, which replaces the first occurrence of that exact string. Obviously, " [0-9]{3} " does not occur in your string.
To use regex, create a Regex
object and pass it to replaceFirst
. This will call the overload that takes a Regex
:
val replaced = "there are 400 pictures".replaceFirst(Regex(" [0-9]{3} "), " a lot of ")
println(replaced) // there are a lot of pictures
See all the overloads here.
Upvotes: 4