kotlin
  1. kotlin-regex-patterns

Kotlin Regex Patterns

Regex (regular expression) patterns are used for pattern matching and manipulating strings. Kotlin supports regex patterns through its built-in Regex class. In this tutorial, we'll explore how to use regex patterns in Kotlin.

Syntax

To use a regex pattern in Kotlin, create a Regex object by providing the pattern string as an argument to the Regex() function. You can then use this object to match patterns in strings using the matchEntire() or find() functions.

val pattern = Regex(patternString)
val matchResult = pattern.matchEntire(inputString)
val matchResult2 = pattern.find(inputString)

Example

Suppose we want to check if a given string is a valid email address. We can use the following regex pattern to match the format of email addresses:

val emailPattern = Regex("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}")
val email = "example@email.com"
val isValidEmail = emailPattern.matchEntire(email) != null

The above code creates a Regex object for the email pattern, then uses the matchEntire() function to match the email string with the pattern. If the matchEntire() function returns a non-null value, it means that the email string matches the pattern and is considered a valid email address.

Output

In the above example, the isValidEmail variable will be set to true if the email string matches the email pattern.

Explanation

A regex pattern is a sequence of characters that define a pattern for matching strings. In the above example, the email pattern consists of three parts:

  • [a-zA-Z0-9.%+-]+: matches one or more alphanumeric characters, ".", "", "%", "+", or "-" before the "@" symbol.
  • @[a-zA-Z0-9.-]+: matches one or more alphanumeric characters, ".", or "-" after the "@" symbol.
  • .[a-zA-Z]{2,}: matches a "." followed by two or more alphabetic characters at the end of the string.

The pattern matching is performed using the matchEntire() or find() functions of the Regex class in Kotlin.

Use

Regex patterns in Kotlin can be used for a wide range of tasks, including validating input data, extracting information from strings, and manipulating strings.

Important Points

  • Ensure that the regex pattern is correctly defined to avoid unexpected results or exceptions.
  • Be aware that some regex patterns can be expensive in terms of computational resources, especially if used on large strings.

Summary

In this tutorial, we looked at how to use regex patterns in Kotlin. We reviewed the syntax, example, output, explanation, use, and important points of working with regex patterns in Kotlin. With the knowledge gained from this tutorial, you should be able to apply regex patterns in your Kotlin projects for text manipulation and validation.

Published on: