In this tutorial, you shall learn how to check if a string matches given regular expression in Kotlin, using String.matches() function, with examples.

Kotlin – Check if String matches Regular Expression

To check if a string matches given regular expression in Kotlin, call matches() method on this string and pass the regular expression as argument. matches() returns true if the string matches with the given regular expression, or else it returns false.

Examples

In the following example, we take a string in str, and check if this string matches regular expression [0-9]+ using matches() method.

Main.kt

fun main(args: Array<String>) {
    var str = "9876543210"
    var re = Regex("[0-9]+")
    var result = str.matches(re)
    println(result)
}

Output

true

Now, let us take another string that does not match the regular expression [0-9]+.

Main.kt

fun main(args: Array<String>) {
    var str = "987-654-3210 hello"
    var re = Regex("[0-9]+")
    var result = str.matches(re)
    println(result)
}

Since, the string contains characters other than numbers from 0-9, matches() returns false.

Output

false
ADVERTISEMENT

Conclusion

In this Kotlin Tutorial, we learned how to check if a string matches given regular expression using String.matches() method, with the help of Kotlin example programs.