0
0
Kotlinprogramming~30 mins

Regular expressions with Regex class in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Regular expressions with Regex class
📖 Scenario: You are working on a simple text processing tool that needs to find specific patterns in user input. Regular expressions help you search for patterns like email addresses or phone numbers easily.
🎯 Goal: Build a Kotlin program that uses the Regex class to find all words starting with the letter 'a' in a given sentence.
📋 What You'll Learn
Create a string variable with a sentence containing multiple words
Create a Regex object to find words starting with 'a'
Use the findAll method of Regex to get all matches
Print all matched words separated by commas
💡 Why This Matters
🌍 Real World
Regular expressions are used in many apps to find patterns like emails, phone numbers, or keywords in text.
💼 Career
Knowing how to use Regex in Kotlin helps you build apps that process and validate text input efficiently.
Progress0 / 4 steps
1
Create the sentence string
Create a string variable called sentence and set it to the exact value: "An apple a day keeps the doctor away"
Kotlin
Need a hint?

Use val sentence = "An apple a day keeps the doctor away" to create the string.

2
Create the Regex pattern
Create a Regex object called pattern with the exact pattern "\\ba\\w*" to find words starting with the letter 'a'.
Kotlin
Need a hint?

Use val pattern = Regex("\\ba\\w*") to create the regex.

3
Find all matches using Regex
Use the findAll method of pattern on sentence and assign the result to a variable called matches.
Kotlin
Need a hint?

Use val matches = pattern.findAll(sentence) to get all matches.

4
Print all matched words
Print all matched words separated by commas by mapping matches to their value and joining them with ", " inside a println.
Kotlin
Need a hint?

Use println(matches.map { it.value }.joinToString(", ")) to print the words.