Regex: Get substring before character pattern

I have a string: all first text here!\nmore text here...

How can i get all the substring before \n so i would get: all first text here!

If you want to get the substring before a specific string you can use substringBefore()

fun main() {
//sampleStart
    val text = "all first text here!\nmore text here..."
    println(text.substringBefore('\n'))
//sampleEnd
}

For a substring before a specific regex I don’t think there is any function in the stdlib.

2 Likes

oh wow! that’s it? thank you!

For something more complex that does require a regex you can precede the regex of what you are looking for with a capture group:

val s = "all first text here!\nmore text here..."
val regex = Regex("^(.*)\n")
val match = regex.find(s)

println(match?.groups?.first()?.value)
1 Like

That would contain the \n though, wouldn’t it? Maybe it’s easier to query the index of the first occurrence and then using substring.

fun main() {
//sampleStart
val s = "all first text here!\nmore text here..."
val match = Regex("\n").find(s)

val firstPart = match?.range?.start?.let { s.substring(0, it)}
println(firstPart)
//sampleEnd
}
1 Like

thank you! this is really helpful.

Yes, sorry, I was trying to get fancy with nullability and said first() when I really wanted group 1. So that should have been:

println(match?.groups?.get(1)?.value)