Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin Regular Expression

Regular Expressions (Regex) are powerful tools for text processing. They provide a means to search, match, and manipulate text. Kotlin, like many programming languages, has built-in support for regular expressions, and it's pretty easy to use once you get the hang of it.

1. Creating a Regex Pattern:

In Kotlin, you can create a Regex object by invoking the toRegex() function on a string:

val regex = "\\d+".toRegex()  // Matches one or more digits

Or you can use the Regex constructor directly:

val regex = Regex("\\d+")

2. Matching Strings:

Use the matches function to check if an entire string matches a given regex:

val isMatch = regex.matches("12345")  // true

3. Finding Matches:

To find occurrences of a pattern within a string, use the find or findAll functions:

val result = regex.find("abc123def456")
println(result?.value)  // Outputs: 123

val allResults = regex.findAll("abc123def456")
for (match in allResults) {
    println(match.value)  // Outputs: 123 and then 456
}

4. Grouping:

You can group parts of your regex pattern using parentheses. This can be useful to extract specific portions of a match:

val pattern = "(\\d+)-(\\d+)".toRegex()
val match = pattern.matchEntire("123-456")

if (match != null) {
    println(match.groupValues[1])  // Outputs: 123
    println(match.groupValues[2])  // Outputs: 456
}

5. Replacing:

To replace occurrences of the regex pattern in a string, use the replace function:

val result = "\\d+".toRegex().replace("abc123def456", "X")
println(result)  // Outputs: abcXdefX

You can also use matched groups in the replacement:

val result = "(\\d+)-(\\d+)".toRegex().replace("123-456", "$2-$1")
println(result)  // Outputs: 456-123

6. Splitting:

To split a string based on a regex pattern, use the split function:

val parts = "\\s+".toRegex().split("One Two Three")
println(parts)  // Outputs: [One, Two, Three]

7. Some Common Regex Symbols:

  • .: Matches any single character (except newline).
  • ^: Matches the beginning of a line or string.
  • $: Matches the end of a line or string.
  • *: Matches 0 or more of the preceding token.
  • +: Matches 1 or more of the preceding token.
  • ?: Matches 0 or 1 of the preceding token.
  • {n}: Matches exactly n of the preceding token.
  • {n,}: Matches n or more of the preceding token.
  • {n,m}: Matches between n and m of the preceding token.
  • \\d: Matches any digit, equivalent to [0-9].
  • \\D: Matches any non-digit.
  • \\w: Matches any word character (alphanumeric and underscore).
  • \\W: Matches any non-word character.
  • \\s: Matches any whitespace character (spaces, tabs, line breaks).

Summary:

Regular expressions in Kotlin are straightforward to use and very powerful. They provide a flexible way to search, manipulate, and validate strings. It's worth noting, however, that complex regular expressions can become hard to read and maintain, so always make sure to comment and document your regex patterns.

  1. Regex pattern matching in Kotlin:

    • Perform basic pattern matching.
    val pattern = "Kotlin".toRegex()
    val isMatch = pattern.matches("Kotlin is awesome!")
    
  2. Creating regex patterns in Kotlin:

    • Build custom regex patterns.
    val customPattern = Regex("[0-9]{3}-[0-9]{2}")
    
  3. Using the Regex class in Kotlin:

    • Utilize the Regex class for regex operations.
    val regex = Regex("[a-zA-Z]+")
    val matches = regex.findAll("Hello Kotlin, meet Regex")
    
  4. Matching and extracting groups in Kotlin regex:

    • Capture and extract groups from matched patterns.
    val regexWithGroups = Regex("(\\d+)-(\\d+)")
    val result = regexWithGroups.find("Age: 25-30")?.groupValues
    
  5. Regex options and flags in Kotlin:

    • Use options and flags for case-insensitive, multiline matching, etc.
    val caseInsensitiveRegex = Regex("kotlin", RegexOption.IGNORE_CASE)
    
  6. Working with quantifiers in Kotlin regex:

    • Specify repetitions with quantifiers.
    val repeatedPattern = Regex("a{2,4}")
    
  7. Character classes and ranges in Kotlin regex:

    • Match characters within specified ranges.
    val charClassRegex = Regex("[A-Za-z0-9]")
    
  8. Anchors and boundaries in Kotlin regex:

    • Define anchors to match the start and end of a string.
    val startOfStringRegex = Regex("^Kotlin")
    
  9. Regex metacharacters in Kotlin:

    • Understand and use metacharacters for special meanings.
    val specialCharRegex = Regex("\\d{3}[-\\.\\s]\\d{2}")
    
  10. Replacing and manipulating strings with regex in Kotlin:

    • Perform string manipulation using regex.
    val replacedString = "Replace digits: 12345".replace(Regex("\\d+"), "X")
    
  11. Validating input with regex in Kotlin:

    • Validate user input against a regex pattern.
    val emailRegex = Regex("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}")
    val isValidEmail = emailRegex.matches("user@example.com")
    
  12. Regex and Kotlin's string interpolation:

    • Combine regex with string interpolation for dynamic patterns.
    val dynamicPattern = Regex("${userInput}\\d{3}")