In this article, we will learn about Regex in Kotlin. Regex is used to refer to a regular expression that is used to search a string or replace a pattern in a String. To use it, we need Regex(pattern: String) class and Kotlin.regex.text package.

Constructor
Regex(pattern: String) | It will give string pattern. |
Regex(pattern: String, option: RegexOption) | It will give string pattern and single option. |
Regex(pattern: String, options: Set<RegexOption>) | It will give a string pattern and a set of giving options. |
Properties
Following are the properties of Regex Kotlin
val options: Set<RegexOption> | It contains the set of options that are to be used at the time of regex creation. |
val pattern: String | It contains the string describing the pattern. |
Regex Functions
Some of the following functions are as fellows
containsMatchIn() | This function returns a Boolean indicating whether there exists any match of our pattern in the input. |
fun containsMatchIn(input: CharSequence): Boolean
Example to demonstrate containsMatchIn() function in Kotlin
fun main()
{
// Regex to match any string starting with 'a'
val pattern = Regex("^a")
println(pattern.containsMatchIn("abc"))
println(pattern.containsMatchIn("bac"))
}
Output
true
false
find() | This function returns the first matched substring pertaining to our pattern in the input, from the specified starting index. |
fun find(input: CharSequence, startIndex: Int): MatchResult?
Example to demonstrate find() function in Kotlin
fun main()
{
// Regex to match "ll" in a string
val pattern1 = Regex("ll")
val ans : MatchResult? = pattern1.find("HelloWorld", 1)
println(ans?.value)
}
Output
ll
Kotlin is quickly becoming a complete modern programming language. In this article, we learned about Regex in Kotlin.