3

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()
2
  • Does the pattern repeat? If your source is "abckey123abckey123", what do you expect? Removing the first key, "123abckey123", or all key "123' Commented Jun 24, 2019 at 2:35
  • it really depends what you want to accomplish... if there is a pattern, then a convenient approach is to use regex with groups and extract those groups instead... e.g. """(.*?)?key(\d+)""".toRegex().findAll(yourInputString).map { it.destructured }.forEach { (firstPart, secondPart) -> println("$firstPart -> $secondPart") }... In this example the regex extracts everything before the last key into group 1 and every digit after key to group 2. So with an input of somekey123 it would print some -> 123 and with somekeykey123 it would print somekey -> 123. Commented Jun 24, 2019 at 7:42

2 Answers 2

6

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

1 Comment

Thanks, this is exactly what I wanted. With substringAfterLast and the before methods as well, this is great.
1
val result = "abckey123".replace(".*key".toRegex(), {""})
println(result)

it gives 123

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.