Reputation: 2655
I have a common pattern where I want to operate on a string like abckey123
where I want to clear the string before key
but also remove the key
.
Is there a commonly accepted way to do this? Or even better a way to make this a single method call on all string objects?
Ideas:
item.replaceBefore("key", "").replace("key", "")
item.split("key").last()
Upvotes: 3
Views: 5216
Reputation: 2252
val result = "abckey123".replace(".*key".toRegex(), {""})
println(result)
it gives 123
Upvotes: 1
Reputation: 23125
If you want to get all text after the "key" substring, you can use substringAfter
function:
val result = item.substringAfter("key")
The second parameter of this function allows to specify what to return if the delimiter is not found. By default it returns the entire string, but you can pass an empty string for example:
val result = item.substringAfter("key", "")
Upvotes: 6