Kotlin String - find() Function



The Kotlin string find() function with a Regex parameter is a method of the Regex class and is used to find the first match of regular expression in a string.

This function is not a direct function of the Kotlin string class but it is invoked via a regex object.

Use Cases of the Find() Function

There are the following use cases of this function −

  • Finding the first occurrence of a pattern in a string.
  • Extracting specific substrings based on a regular expression.

Syntax

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

fun Regex.find(input: CharSequence, startIndex: Int = 0): MatchResult?

Parameters

This function accepts following parameters −

  • CharSequence: The string or charSequence in which we search for a match.
  • startIndex: It is an optional parameter that represents an index from which we start searching in a string. The default is 0.

Return value

If a match is found this function returns the first match as a MatchResult object. Otherwise, returns null if no match is found.

Example 1: Find a Word in String

Following is the basic example of find() function: Find a word in a string −

fun main() {
   val regex = Regex("\\btutorialspoint\\b")
   val string = "I love tutorialspoint"
   val match = regex.find(string)
   
   println(match?.value)
}

Output

Following is the output −

tutorialspoint

Example 2: Use Start Index to Find a Pattern

Let's see another example of the find() function: Finding a Match with a Specific Start Index −

fun main() {
   val regex = Regex("\\d+")
   val input_str = "abc123def456"
   val match = regex.find(input_str, startIndex = 6)
   
   println(match?.value)
}

Output

Following is the output −

456

Example 3: Check Regex Pattern

This example uses the find() function to check the regex pattern using capturing groups −

fun main() {
   // Matches a format like "123-45-6789"
   val regex = Regex("(\\d{3})-(\\d{3})-(\\d{4})")
   val input_str = "This is my number 913-045-6788."
   val match = regex.find(input_str)
   
   if (match != null) {
      println("Full match: ${match.value}")
      println("First group: ${match.groups[1]?.value}")
      println("Second group: ${match.groups[2]?.value}")
      println("Third group: ${match.groups[3]?.value}")
   }
}

Output

Following is the output −

Full match: 913-045-6788
First group: 913
Second group: 045
Third group: 6788
kotlin_strings.htm
Advertisements