Kotlin String - matches() Function



The Kotlin string matches() function is used to check whether the entire character sequence contains the specified regular expression. Return true if the character sequence matches the regex.

Use Cases of Matches()

There are the following use cases of this function −

  • Validating Patterns: It validate if a string matches a specific pattern like email, address, phone number, etc.
  • Form Validation: This is ideal for ensuring that user input follows a predefined structure.
  • Regex-based Matching: Useful for pattern-based logic in programs.

Syntax

Following is the syntax of the Kotlin string matches() function −

fun CharSequence.matches(regex: Regex): Boolean

Parameters

This function accepts 'regex' as parameters, representing the regular expression we want to check against the character sequence.

Return value

This function returns true if the character sequence matches the regex; otherwise, returns false.

Example 1: Validate an Alphabetic String

Following is the basic example of the matches() function: If string only contains alphabetic character return "true" −

fun main() {
   val regex = Regex("^[a-zA-Z]+$")
   
   val string = "tutorialspoint"    
   println(string.matches(regex))

   val invalidInput = "Kotlin123"
   println(invalidInput.matches(regex))
}

Output

Following is the output −

true
false

Example 2: Validate an Email

Let's see another example of the matches() function to validate an email −

fun main() {
   val emailRegex = Regex("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$")
   
   val validEmail = "example@test.com"
   println("Is this email valid? " + validEmail.matches(emailRegex))

   val invalidEmail = "example@com"
   println("Is this email valid? " + invalidEmail.matches(emailRegex))
}

Output

Following is the output −

Is this email valid? true
Is this email valid? false

Example 3: Checking Numeric Input

Now, let's see another example of the matches() function: Checking Numeric input −

fun main() {
   val numberRegex = Regex("^\\d+$")
   
   val validNumber = "12345"
   println("Is this valid numeric string? " + validNumber.matches(numberRegex))

   val invalidNumber = "123abc"
   println("Is this valid numeric string? " + invalidNumber.matches(numberRegex))
}

Output

Following is the output −

Is this valid numeric string? true
Is this valid numeric string? false
kotlin_strings.htm
Advertisements