Mastering Regular Expressions in Kotlin: A Step-by-Step Guide

What is RegEx?

Regular expressions, commonly known as RegEx, are a powerful tool for validating and manipulating strings. It’s a crucial skill for any developer, as it can simplify complex string manipulation tasks and improve code efficiency.

Basic RegEx Patterns in Kotlin

Before we dive into the advanced topics, let’s cover some basic RegEx patterns in Kotlin:


// Matching a string
val regex = Regex("Hello")
println(regex.matches("Hello")) // true

// Matching a pattern
val regex = Regex("[a-zA-Z]+")
println(regex.matches("HelloWorld")) // true

RegexOption (IGNORE_CASE)

In Kotlin, you can use the RegexOption.IGNORE_CASE flag to make your RegEx patterns case-insensitive:


val regex = Regex("hello", RegexOption.IGNORE_CASE)
println(regex.matches("HELLO")) // true

Mobile Number Validation

Let’s create a simple app that validates mobile numbers using RegEx. We’ll use the following pattern to match Nigerian phone numbers:


val pattern = Regex("^0(7|8|9|1)\\d{9}$")

This pattern matches numbers starting with 07, 08, 09, or 01, followed by 9 digits.

Binding Kotlin to XML

To bind our Kotlin code to XML, we’ll use the ViewBinding feature. This allows us to access our views directly from our Kotlin code:


private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
}

Explaining the Code Snippet

In our MainActivity.kt file, we’ll use the TextWatcher interface to monitor changes to the EditText:


binding.edit.addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        val input = s.toString()
        val isValid = mobileValidate(input)
        binding.button.isEnabled = isValid
    }

    override fun afterTextChanged(s: Editable?) {}
})

The mobileValidate function checks if the input matches our RegEx pattern:


fun mobileValidate(input: String): Boolean {
    val pattern = Regex("^0(7|8|9|1)\\d{9}$")
    return pattern.matches(input)
}

Leave a Reply

Your email address will not be published. Required fields are marked *