Hi all, Does anyone know how to do a partial match...
# multiplatform
d
Hi all, Does anyone know how to do a partial match of a string against a
Regex
in Kotlin multiplatform? Or said in other words, how can I know if a
String
could potentially match the
Regex
? similar to what can be accomplished with
java.util.regex.Matcher.hitEnd()
As said, what I’m doing right now with
java.util.regex.Matcher
for Kotlin/JVM target is:
Copy code
fun Regex.partialMatch(input: String): Boolean {
    val matcher: Matcher = toPattern().matcher(input)
    return if (matcher.matches()) { true } else { matcher.hitEnd() }
}
But I have tried several things and couldn’t find any way of of doing it on KMP. For example: given this
Regex
of a date format (like ‘mm/dd/yyyy’ or ‘dd/mm/yyyy’):
Copy code
val regex = Regex("[0-9]{2}/[0-9]{2}/[0-9]{4}")
regex.partialMatch("01") // true
regex.partialMatch("01/02") // true
regex.partialMatch("01/02/20") // true
regex.partialMatch("01/02/2023") // true
regex.partialMatch("000") // false
Any ideas?
a
try
regex.containsMatchIn("01")
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-regex/contains-match-in.html edit: oh, I looked properly at your examples now, you want some sort of
String.startsWith(regex)
?
d
Yes, sort of
a
try updating the regex so that everything after the first digit is optional. Then if a string doesn’t match matches, then it’s considered a partial match.