Published on

Regex in Kotlin

Authors

Kotlin has a class called Regex specifically ,you'd guested it!!, for handling regular expressions. At first glance it seems to basically be a wrapper around the Java Matcher class but like many things in Kotlin it adds a whole bunch of extension functions on the standard Java class to make working with regex easier.

To use the Regex you can do it in a similar way to using a matcher in Java:

val text = "The quick brown fox jumps over the lazy dog"
val result =
Regex(".*fox (\\w+) .*")
   .matchEntire(text)
   ?.groupValues
   ?.get(1)

println(result)
jumps

The api is a bit cleaner as you do not have to call matcher.find() or anything else before accessing the results of the match. Kotlin's inbuilt null handling operators makes dealing with potentially no matches much easier. In the above if there was no match null would be returned, but as with all null handling in Kotlin you can make the above return a value or execute code if it is null by placing ?: after get(1).

If you were wondering how to match a string that has Kotlin string template characters in then the answer is quite simple, you escape those characters like you would any others in strings in Java. So for example if I want regex that matches something in-between ${ and } you would simply write it as follows:

val textWithTemplateLiterals = "blah blah \${test} abc 123"

val resultForTemplateLiteralsString =
Regex(".*\\$\\{(.*)\\}.*")
   .matchEntire(textWithTemplateLiterals)
   ?.groupValues
   ?.get(1)
println(resultForTemplateLiteralsString)
test

Notice how you need to escape it twice. One escape character is to say treat it as a dollar symbol and not a Kotlin string template but $ has special meaning in regex so you have to escape it once more.

I have only played around with the basic regex features but I see that there are many more methods available which as with most things in Kotlin I am sure makes working with regex even easier and less error prone than with the old school Java approach.