Kotlin Regular Expression

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 preceeding 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

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main()
{
    // Regex to match any string starting with 'a'
    val pattern = Regex("^a")
    println(pattern.containsMatchIn("abc"))
    println(pattern.containsMatchIn("bac"))
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main()
{
    // Regex to match "ll" in a string
    val pattern1 = Regex("ll")
    val ans : MatchResult? = pattern1.find("HelloHello", 5)
    println(ans ?.value)
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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()
}

chevron_right


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


filter_none

edit
close

play_arrow

link
brightness_4
code

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"))
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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)
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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()
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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) }
}

chevron_right


Output:

This
is
a
sentence


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.