Say I have a string
"Hello! How do you do? Good day!"
and I want to split it, with my delimiters being: ?
and !
using the "split" function the result would be:
`[Hello, How do you do, Good day]`
However, I want it to be:
`[Hello, !, How do you do, ?, Good day, !]`
Here is a similar question in Java: How to split a string, but also keep the delimiters?
Use lookahead. In Kotlin, the code maybe like this:
fun main(args: Array<String>) {
val str = "Hello! How do you do? Good day!"
val reg = Regex("(?<=[!?])|(?=[!?])")
var list = str.split(reg)
println(list)
}
The output of this is:
[Hello, !, How do you do, ?, Good day, !]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With