Open In App

Kotlin Regular Expression

Last Updated : 22 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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
 

Constructors –

  1. <init>(pattern: String): This constructor creates a regular expression based on the pattern string. 
     
  2. <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. 
     
  3. <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. 
     

Properties –

  1. val options: Set<RegexOption> : It contains the set of options which are to be used at the time of regex creation. 
     
  2. val pattern: String : It contains the string describing the pattern. 
     

Regex Functions –

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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads