Signup/Sign In

Kotlin Regular Expression

In this tutorial we will discuss about regular expressions in Kotlin. A regular expression is a sequence of characters which used is to define a pattern. This pattern is also known as a regex.

A regex can be used for many things like pattern matching in string, find and replace in strings etc. In Kotlin, Regex class is used to create and manage regular expressions.

Kotlin Create Regular Expression

To define a regular expression, we will create an object of Regex class. The pattern to create username which contains only alphanumeric characters (with at least one length) is:

val usernamePattern = "[a-zA-Z0-9]+"

A regular expression object with a pattern can be created in multiple ways:

1. Regex constructor

The regex pattern is passed as the parameter to the constructor:

val usernamePattern = "[a-zA-Z0-9]+"
val regex = Regex(usernamePattern)

2. Using toRegex() function

Calling toRegex() function to create a regex object:

val usernamePattern = "[a-zA-Z0-9]+"
val regex = usernamePattern.toRegex()

3. Using fromLiteral() function

We can also use fromLiteral() function to create a regex. This function returns a regular expression that matches the specified pattern string literally. It means no characters of that string will have special meaning. So /w will be considered as /w string only and not a metacharacter:

val usernamePattern = "[a-zA-Z0-9]+"
val regex = Regex.fromLiteral(usernamePattern)

Using any of the three methods, we can create a regex object. Now let us see how to perform operation on it.

Match Partial String

Let us see how we can match partial string using regex. If a substring of input matches the regex then we will get true:

fun main() {
    val usernamePattern = "[a-zA-Z0-9]+"
    val regex = Regex(usernamePattern)
    println(regex.containsMatchIn("Ninja__Nin"))
    println(regex.containsMatchIn("!#$%"))
}


true
false

In first case after matching only first character 'N' we will get true. But in second case, not even a single substring matches the pattern. Hence, we get false.

Match Complete String

To match full string with a regex we can use matches() function or matches infix operator. They will return true only if complete string satisfies the pattern:

fun main() {
    val usernamePattern = "[a-zA-Z0-9]+"
    val regex = Regex(usernamePattern)
    println(regex.matches("Ninja"))
    println(regex matches "Ninja")
    println(regex.matches("Ninja__Nin"))
}


true
true
false

Here the first and second string follows the patterns and hence returns true. In second case, the string contains _ hence we get false.

Extract partial matching string

If we wants to match and then extract partial matching strings, we can use find() and findAll() functions. The find() function returns the object of MatchResult containing first matching substring or null if none exists. The findAll() function return the set of MatchResult containing all matching substrings:

fun main() {
    val usernamePattern = "[a-zA-Z0-9]+"
    val regex = Regex(usernamePattern)
    println(regex.find("Nin_ja")?.value)
    regex.findAll("Ninja__Nin-123").forEach {
        println(it.value)
    }
}


Nin
Ninja
Nin
123

Extract complete matching string

If we wants to match and then extract complete matching string, we can use matchEntire() function. It will return object of MatchResult class containing string.

fun main() {
    val usernamePattern = "[a-zA-Z0-9]+"
    val regex = Regex(usernamePattern)
    println(regex.matchEntire("Ninja")?.value)
}


Ninja

Summary

In this tutorial we discussed about Kotlin Regex. We saw how to create regex object and use them for matching patterns. In the next tutorial we will discuss about Kotlin operator overloading.



About the author:
I'm a writer at studytonight.com.