Kotlin Regular Expression

22 Sep, 2021
Regular Expressions are a fundamental part of almost every programming language and Kotlin is no exception to it. In Kotlin, the support for regular expression is provided through Regex class. An object of this class represents a regular expression, that can be used for string matching purposes.  
class Regex
We can easily find use of regular expressions in different kind of software, from simplest to incredibly complex applications. Before preceding this article have a look at Regular Expression in Java 
<init>(pattern: String): This constructor creates a regular expression based on the pattern string.  <init>(pattern: String, option: RegexOption): This constructor creates a regular expression based on the specified pattern and the option. The option is a constant of RegexOption enum class.  <init>(pattern: String, options: Set<RegexOption>): This constructor creates a regular expression on the basis of the specified string pattern and the set of options specified in the set.  
<init>(pattern: String): This constructor creates a regular expression based on the pattern string.  
<init>(pattern: String, option: RegexOption): This constructor creates a regular expression based on the specified pattern and the option. The option is a constant of RegexOption enum class.  
<init>(pattern: String, options: Set<RegexOption>): This constructor creates a regular expression on the basis of the specified string pattern and the set of options specified in the set.  
val options: Set<RegexOption> : It contains the set of options which are to be used at the time of regex creation.  val pattern: String : It contains the string describing the pattern.  
val options: Set<RegexOption> : It contains the set of options which are to be used at the time of regex creation.  
val pattern: String : It contains the string describing the pattern.  
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 
Java
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 
Java
fun main(){    // Regex to match "ll" in a string    val pattern1 = Regex("ll")    val ans : MatchResult? = pattern1.find("HelloHello", 5)    println(ans ?.value)}
Output: 
ll
findAll() – This function returns all the matchings of the specified pattern in the input, searching from the given start index. 
fun findAll(
    input: CharSequence, 
    startIndex: Int
): Sequence
Example to demonstrate findAll function in Kotlin 
Java
fun main(){    // Regex to match a 3 letter pattern beginning with ab    val pattern2 = Regex("ab.")    val ans1 : Sequence<MatchResult> = pattern2.findAll("abcfffgdbabs", 0)    // forEach loop used to display all the matches    ans1.forEach()    {            matchResult -> println(matchResult.value)    }    println()}
Output: 
abc
abs
matches() – This function returns a boolean indicating whether the input string completely matches the pattern or not.  
infix fun matches(input: CharSequence): Boolean
Example to demonstrate matches() function in Kotlin 
Java
fun main(){    // Tests demonstrating entire string match    val pattern = Regex("g([ee]+)ks?")    println(pattern.matches("geeks"))    println(pattern.matches("geeeeeeeeeeks"))    println(pattern.matches("geeksforgeeks"))}
Output:  
true
true
false
matchEntire() – This function tries to match the entire input to the specified pattern string, returning the string if it matches. If does not match the string, return null.  
fun matchEntire(input: CharSequence): MatchResult?
Example to demonstrate matchEntire() function in Kotlin 
Java
fun main(){    // Tests demonstrating entire string match    var pattern = Regex("geeks?")    println(pattern.matchEntire("geeks")?.value)    println(pattern.matchEntire("geeeeeeeks")?.value)    pattern = Regex("""\D+""")    println(pattern.matchEntire("geeks")?.value)    println(pattern.matchEntire("geeks12345")?.value)}
Output: 
geeks
null
geeks
null
replace() – This function replaces all the occurrences of the pattern in the input string with the specified replacement string.  
fun replace(input: CharSequence, replacement: String): String
replaceFirst() – This function replaces the first match of the regular expression in the input with the replacement string.  
fun replaceFirst(
    input: CharSequence, 
    replacement: String
): String
Example to demonstrate replace() and replaceFirst() functions in Kotlin 
Java
fun main(){    // Tests demonstrating replacement functions    val pattern4 = Regex("xyz")    // replace all xyz with abc in the string    println(pattern4.replace("xyzxyzzzzzzzzz", "abc"))    // replace only first xyz with abc not all    println(pattern4.replaceFirst("xyzddddddxyz", "abc"))    println()}
Output:  
abcabczzzzzzzz    // replace all
abcddddddxyz      // replace first matching only
split() – This function breaks the input string into tokens according to the specified parameter.  
fun split(input: CharSequence, limit: Int): List
Example to demonstrate split() function in Kotlin 
Java
fun main(){    // Tests demonstrating split function    val pattern = Regex("\\s+")  // separate for white-spaces    val ans : List<String> = pattern.split("This is a sentence")    ans.forEach { word -> println(word) }}
Output: 
This
is
a
sentence
ruhelaa48
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Retrofit with Kotlin Coroutine in Android
Kotlin constructor
How to Communicate Between Fragments in Android?
Kotlin Setters and Getters
How to Add and Customize Back Button of Action Bar in Android?
Suspend Function In Kotlin Coroutines
How to Change the Color of Status Bar in an Android App?
Kotlin when expression