CodeBlanks Logo Icon CodeBlanks

Regex

Learn regular expressions with Regex.

Regex: matching with patterns

In Kotlin the Regex class matches text against a pattern. A pattern is a string with special symbols: \d digit, \w letter digit underscore, + one or more, * zero or more.

val digits = Regex("\\d+")
val result = digits.matches("12345")
// true

Inside a normal string you must double the backslash. With a raw string a single backslash is enough. Regex is ideal for validating phone, email or date-like strings.

Using the Regex class

A Regex object is created with Regex(pattern). If you use the same pattern many times, store it in a variable so it is not recompiled.

val phone = Regex("\\d{3}-\\d{4}")
println(phone.matches("555-1234"))
// true

In a pattern {n} means exactly n times, {n,m} means at least n at most m. This lets you write fixed-length patterns easily. Define the pattern once, then match as many times as you need.

Practice Test with a Regex

Define a Regex that matches one or more digits. Test the string "2024" with matches and print the result.

Starter code

Main.kt
fun main() {
    // Define a Regex: one or more digits
    // Test the string "2024" with matches
}

Sample solution

Main.kt
val r = Regex("\\d+")
println(r.matches("2024"))

Expected output

true

Questions and answers

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

1 Match pattern to meaning

Term Meaning
\d Digit
\w Letter digit underscore
+ One or more
* Zero or more

2 Fill in the blank: define a Regex

Question
val r = ____("\\d+")
Answer
val r = Regex("\\d+")

Explanation: Regex(pattern) creates a new pattern object.

3 Which pattern captures the digits in 'abc123'?

Main.kt
val r = Regex("\\d+")
  • \d?
  • \w-
  • [abc]+
  • \d+ Correct answer

Explanation: \d+ matches one or more digits.

All lessons in Beginner