Using Regex in a when


In Scala it’s very easy to perform pattern matching on a regex:

val regex = "varchar\\((\\d+)\\)".r
val string = "varchar(255)"

string match {
 case regex(precision) => println(precision)
 case other => println("not a varchar")

What’s the closest equivilent in Kotlin? Something like using a regex in a when would be ideal, but if not, then other tips would be good.


I would write

 val regex = Regex("varchar\\((\\d+)\\)")
  val string = "varchar(255)"

  val match = regex.matchEntire(string)
  if (match != null) {
    val (precision) = match.destructured
  } else {
    println("not a varchar")

If you don’t need “else” branch, it might be shorter:

  regex.matchEntire(string)?.let { match ->
    val (precision) = match.destructured

Not as short as in Scala, unfortunately.


I can of course use an if else branch. I wasn’t asking how to do regex matching. I was wondering if there was a nice easy way of doing it in a when clause like a Scala pattern match. The reason being is I want to do something like

when (str) {
 "a" ->
 "b" -> 
 regex(c) ->


There are two forms of when. With when (str) you can only do a direct comparison. And simple when is a replacement for a series of if-s, so it’s not better either. Scala is much more powerful in that aspect, you can’t do unapply in Kotlin, unfortunately. There are some rudimentary forms with destructuring operator, but it can’t be used with when and it is quite limited.


I think this is something that should be considered to be added. Pattern matching like this is one of the best parts of Scala and, imo, would be a welcome addition to Kotlin, in whatever form it would be.

operator fun Regex.contains(text: CharSequence): Boolean = this.matches(text)

when("Alex") {
  in Regex(".+lex") -> { println("ends with lex") }