CodeBlanks Logo Icon CodeBlanks

matches and find

Learn regex search with matches and find.

matches and find: two ways to match

matches requires the whole string to fit the pattern; find searches inside the string and returns the first match.

val r = Regex("\\d+")
r.matches("123")   // true — all digits
r.matches("a12")   // false — not all digits
r.find("a12b")?.value  // "12" — first match

find returns null when nothing matches; that is why ?.value uses a safe call. Use matches to validate a phone, find to pull digits out of a longer text.

findAll: get every match

findAll returns every match in the string as a sequence. Each match is a MatchResult whose value holds the matched text.

val r = Regex("\\d+")
val list = r.findAll("a1b22c333").map { it.value }.toList()
// ["1", "22", "333"]

map turns each match into its value; toList collects them into a list. This is how you extract numbers, tags or codes from a text.

Practice Find and print the first digit

With Regex("\\d+"), call find on "a42b7"; print the value of the match.

Starter code

Main.kt
fun main() {
    val r = Regex("\\d+")
    // Call find for the first match and print its value
}

Sample solution

Main.kt
val r = Regex("\\d+")
println(r.find("a42b7")?.value)

Expected output

42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does Regex("\\d+").matches("abc") return?

  • null
  • true
  • false Correct answer
  • Throws an error

Explanation: matches returns false because the whole string is not digits; not null.

2 Fill in the blank: find first match

Question
val r = Regex("\\d+")
val first = r.____("a1b2")
Answer
val r = Regex("\\d+")
val first = r.find("a1b2")

Explanation: find returns the first match as a MatchResult.

3 Match method to job

Term Meaning
matches Whole must fit
find First match
findAll All matches
?.value Safe access

All lessons in Beginner