boden
boden

Reputation: 1681

How to replaceFirst in Kotlit by regex?

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

Answers (1)

Sweeper
Sweeper

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

Related Questions