v79
10/19/2023, 9:34 PMString.split(regex)
when there are no matches. Does split()
return "the rest of the string" when a regex match fails? Code in 🧵fun main() {
val regex = Regex("-{3} #")
val willMatch = """
---
apple: banana
--- #matches
Yay
"""
val willNotMatch = """
---
Not a valid match
"""
println("Find the number of matches")
println(regex.findAll(willMatch).count()) // expect 1, got 1
println(regex.findAll(willNotMatch).count()) // expect 0, got 0
println("Split and build a map from the matches. Why does size != count from above?")
println(willMatch.split(regex).map {it.trim()}.associate{it.substringBefore("\n").trim() to it.substringAfter("\n")}.size) // expect 1, got 2
println(willNotMatch.split(regex).map {it.trim()}.associate{it.substringBefore("\n") to it.substringAfter("\n")}.size) // expect 0, got 1
}
ephemient
10/19/2023, 9:41 PMhho
10/19/2023, 9:42 PMIf the expression does not match any part of the input then the resulting array has just one element, namely this string.https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-int-
ephemient
10/19/2023, 9:43 PM"a-b".split('-') == listOf("a", "b")
there is 1 match and 2 resultsv79
10/19/2023, 9:50 PMephemient
10/19/2023, 9:50 PMv79
10/19/2023, 9:53 PMephemient
10/19/2023, 9:54 PM.split().drop(1)
always gets you what you want whether there is a match or notsplit()