Kotlin Regex Patterns

Regular expression is used to search for text and more advanced text manipulation. 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.

We can easily find use of regular expressions in different kind of software, from simplest to incredibly complex applications.

Kotlin regular expression
In Kotlin, we build regular expressions with the Regex.



Regex("pen")
"pen".toRegex()
Regex.fromLiteral("pen")

A pattern defines the text we need to search for or manipulate. It consists of text literals and metacharacters. Metacharacters are special characters that control the evaluation of the regular expression. For example, with \s we search for white spaces.

In Kotlin, some of the regex patterns are given in the table below.

Pattern Concept Example
^ Matches the first character of the string to the given character ^x
$ Matches the last character of the string to the given character x$
. This pattern matches any single character. ab.
| This is known as the alternation/ OR operator. This combines two or more patterns. ^x | a$
? This matches the occurrence of the previous character at most one time. ab?
+ This matches the occurrence of the previous character at least one time. abc+
* This matches the occurrence of the previous character zero or more times. xyz*
[pqr] This matches any single character present in the set. [pqr]
[i-p] This matches any single character within the range. [i-p]
[^fsd] This implies negation. It matches any character except the ones specified. [^fsd]
\s This is the character class that matches whitespaces. \\s+ (Matches one or more whitespace character)
\w This is the character class that matches any character that forms a word. \\w

Note :- First we have create a pattern, then we can use one of the functions to apply to the pattern on a text string. The functions include find(), findall(), replace(), and split().

Kotlin find() method

It returns the first match of a regular expression in the input, starting at the specified start index. In Kotlin, the default start index is 0.

Kotlin program of using find method –

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main(args : Array<String>) {
  
    val company = "GeeksforGeeks : A computer science portal for students"
  
    val pattern = "science".toRegex()
  
    val found = pattern.find(company)
  
    val m = found?.value
    val index = found?.range
  
    println("$m found at indexes: $index")
  
}

chevron_right


Output:

science found at indexes: 27..33

Kotlin findAll() method

It returns a sequence of all the occurrences of a regular expression within the given input string.

Kotlin program of using findAll method –

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main(args : Array<String>) {
  
    val company = "GeeksforGeeks"
  
    val pattern = "Geeks".toRegex()
  
    val patt = pattern.findAll(company)
  
    patt.forEach { f ->
        val m = f.value
        val index = f.range
        println("$m indexes are: $index")
     }
}

chevron_right


Output:

Geeks indexes are: 0..4
Geeks indexes are: 8..1

The dot(.) metacharacter

The dot (.) metacharacter denotes for any of the single character in the text.
Kotlin program –

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main(args : Array<String>) {
  
    val names = listOf("GeeksforGeeks", "GeekyAnts", "McGeek")
  
    val pattern = "..Geek".toRegex()
  
    names.forEach { name ->
        if (pattern.containsMatchIn(name)) {
            println("$name matches")
  
        }
    }
}

chevron_right


Output:

GeeksforGeeks matches
McGeek matches



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.



Improved By : nidhi_biet

Article Tags :

Be the First to upvote.


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