Regex: Get substring before character pattern

#1

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!

#2

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
#3

oh wow! that’s it? thank you!

#4

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
#5

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
#6

thank you! this is really helpful.

#7

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)