Regex In Kotlin

Learn via video courses
Topics Covered

Overview

In Kotlin, regex (regular expressions) are supported through the built-in Regex class, allowing developers to work with pattern matching and text manipulation. The syntax is concise, leveraging string literals and extension functions. Kotlin provides functions like matches() for checking if a string matches a regex pattern and replace() for pattern-based string replacements. The Regex class enables the creation of complex search patterns easily. Kotlin's regex support empowers developers to perform powerful and efficient text processing operations concisely and expressively, contributing to the language's versatility in various applications.

Regex Constructor in Kotlin

In Kotlin, the Regex class is used for working with regular expressions, and it provides a primary constructor that takes a single parameter representing the regular expression pattern. Here's an overview of the regex constructor in Kotlin:

Code:

Output:

Explanation:

  • The regexPattern defines the regular expression pattern for a Social Security Number (SSN).
  • The Regex class is used to create a regex instance (regex) with the specified pattern.
  • The inputString is "123-45-6789," and the matches() function checks if it matches the SSN pattern.
  • Since the input string matches the pattern, the output is "The input string matches the pattern."

Regex Properties in Kotlin

In Kotlin, the Regex class provides various properties that allow you to obtain information about the regular expression pattern. Here are some of the key properties:

  1. pattern: String
    • Returns the original regular expression pattern as a string.
    Code:
    Output:

Explanation:

  • The pattern property returns the original regular expression pattern as a string.
  • In this example, the pattern is a regex for a Social Security Number.
  1. options: Set<RegexOption>
    • Returns a set of regex options applied to the regular expression.
    Code:
    Output:

Explanation:

  • The options property returns a set of regex options applied to the regular expression.
  • In this example, the IGNORE_CASE option is set, allowing case-insensitive matching.
  1. patternLength: Int
  • Returns the length of the regular expression pattern.

Code:

Output:

Explanation:

  • The patternLength property returns the length of the regular expression pattern.
  • In this example, the pattern's length is 16 characters.
  1. namedGroups: Map<String, Int>

    • Returns a map of named groups in the regular expression pattern and their corresponding group indices.

    Code:

    Output:

Explanation:

  • The namedGroups property returns a map of named groups and their corresponding group indices.
  • In this example, named groups for year, month, and day are defined in the regex pattern.

These properties provide useful information about the regex pattern and its configuration, facilitating better understanding and manipulation of regular expressions in Kotlin.

Regex Methods in Kotlin

In Kotlin, the Regex class provides various methods for working with regular expressions. Here are some key methods:

  1. matches(input: CharSequence): Boolean

    • Checks if the entire input sequence matches the regular expression pattern.

    Code:

Output:

Explanation:

  • A Regex instance is created with the pattern \d{3}-\d{2}-\d{4}, representing a Social Security Number.
  • The matches function is used to check if the inputString ("123-45-6789") matches the defined pattern.
  • Since the input string matches the pattern, the output is "The input string matches the pattern."
  1. containsMatchIn(input: CharSequence): Boolean

    • Checks if there is any substring within the input sequence that matches the regular expression pattern.

    Code:

Output:

Explanation:

  • A Regex instance is created with the pattern \d{3}-\d{2}-\d{4}, representing a Social Security Number.
  • The containsMatchIn function is used to check if the inputString contains any substring that matches the defined pattern.
  • Since the input string contains the SSN pattern, the output is "The input string contains a matching pattern."
  1. find(input: CharSequence): MatchResult?

    • Finds the first match of the regular expression pattern in the input sequence.

    Code:

Output:

Explanation:

  • A Regex instance is created with the pattern \d{3}-\d{2}-\d{4}, representing a Social Security Number.
  • The find function is used to find the first match of the pattern in the inputString.
  • If a match is found (matchResult is not null), it prints the value of the first match. In this case, the output is "First match found: 123-45-6789."
  1. findAll(input: CharSequence): Sequence<MatchResult>
    • Finds all occurrences of the regular expression pattern in the input sequence.

Code:

Output:

Explanation:

  • A Regex instance is created with the pattern \d{3}-\d{2}-\d{4}, representing a Social Security Number.
  • The findAll function is used to find all occurrences of the pattern in the inputString.
  • The forEach loop iterates over each MatchResult, and it prints the value of each match. In this case, it prints both SSNs found in the input string.
  1. replace(input: CharSequence, replacement: String): String

    • Replaces the first occurrence of the regular expression pattern in the input sequence with the specified replacement string.

    Code:

Output:

Explanation:

  • A Regex instance is created with the pattern \d{3}-\d{2}-\d{4}, representing a Social Security Number.
  • The replace function is used to replace the first occurrence of the pattern in the inputString with the specified replacement string ("XXX-XX-XXXX").
  • The output is "Replaced string: My SSN is XXX-XX-XXXX." where the original SSN is replaced with the specified pattern.

These methods provide essential functionalities for matching, searching, and replacing text based on regular expression patterns in Kotlin.

Creating a Regular Expression Object

In Kotlin, a regular expression object is created using the Regex class. The Regex class provides a constructor that takes a single parameter, which is a string representing the regular expression pattern. Here's an example of how you can create a regular expression object:

Code:

Output:

Explanation:

  • The Regex class is used to create a regular expression object (regex) with the specified pattern (\d{3}-\d{2}-\d{4}), representing a Social Security Number.
  • The matches function is then used to check if the inputString ("123-45-6789") matches the defined pattern.
  • Since the input string matches the pattern, the output is "The input string matches the pattern."

Adjust the regexPattern based on your specific regular expression requirements, and use the created Regex object to perform pattern matching, searching, or replacing operations on strings.

Checking Matches

In Kotlin, you can check if a string matches a regular expression using the matches() method of the Regex class. Here's an example:

Code:

Output:

Explanation:

  • The Regex class is used to create a regular expression object (regex) with the specified pattern (\d{3}-\d{2}-\d{4}), representing a Social Security Number.
  • The input string is "123-45-6789."
  • The matches function is used to check if the input string matches the defined pattern.
  • Since the input string matches the pattern, the output is "The input string matches the pattern."

Adjust the ssnPattern and inputString based on your specific use case and pattern requirements. The matches() method returns a boolean value (true if there is a match, false otherwise), allowing you to conditionally execute code based on whether the input string conforms to the regular expression pattern.

Examples

Let's explore a few examples of using regular expressions (Regex) in Kotlin:

Example 1: Matching Social Security Numbers

Code:

Output:

Explanation:

  • The Regex class is used to create a regular expression object (regex) with the specified pattern (\d{3}-\d{2}-\d{4}), representing a Social Security Number.
  • Two input strings (input1 and input2) are checked against the SSN pattern using the matches function.
  • Both input strings match the SSN pattern, so the output indicates that they are valid Social Security Numbers.

Example 2: Extracting Email Addresses

Code:

Output:

Explanation:

  • The Regex class is used to create a regular expression object (regex) with the specified pattern, representing an email address.
  • The findAll function is used to find all occurrences of email addresses in the text.
  • The forEach loop iterates over each MatchResult, printing the value of each found email address in the text.

These examples demonstrate basic uses of regular expressions in Kotlin, including pattern matching, extraction, and replacement. Adjust the patterns and input strings based on your specific requirements.

Conclusion

  • Kotlin's Regex class enables developers to define and apply complex patterns for matching strings, allowing for tasks like validation, extraction, and substitution.
  • Regular expressions are represented as Regex objects in Kotlin, created using the Regex class constructor with a pattern string.
  • The matches() method of the Regex class is used to check if a given string matches the specified pattern, providing a straightforward way to validate data.
  • The find() and findAll() methods allow developers to search for and extract substrings that match a pattern within a larger text.
  • The replace() method facilitates the replacement of substrings matching a pattern with a specified replacement string.
  • Regular expressions are versatile tools that can be applied to a wide range of use cases, including validation of input, text processing, and data extraction.