Regex in Kotlin Android Studio

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.

Regex in Kotlin


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.


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: StringIt 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") 


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) 



Kotlin is quickly becoming a complete modern programming language. In this article, we learned about Regex in Kotlin.

Next Article

How to Validate an Email in Kotlin Android

Please share this post:
Posts created 41

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: