Regex Constructors in Kotlin
Three different types of constructors are classified on the number and type of arguments supplied. They are listed as follows:
<init>(pattern: String)
This constructor is used to create a regular expression from the input string pattern.
<init>(pattern: String, option: RegexOption)
This constructor creates a regular expression from the input string pattern and the specified option.
<init>(pattern: String, options: Set<RegexOption>)
This constructor creates a regular expression from the input string pattern and the set of options specified in the input.
To read more about constructors in Kotlin, read the blog Kotlin Constructors on the Coding Ninjas Website.
Regex Functions in Kotlin
containsMatchIn
This function checks whether the regular expression can find at least a single match in the given input string.
The prototype of the containsMatchIn function is as follows.
fun containsMatchIn(input: CharSequence): Boolean
The following program denotes the example usage of this function
// Kotlin program to demonstrate regex containsMatchIn function
fun main(){
val regex = Regex("""Ko""")
var input_str: String = "Kotlin is my favourite programming language"
val is_match = regex.containsMatchIn(input_str)
if(is_match){
println("Match found")
}else{
println("Match not found")
}
}Output:
Match found
find
This function returns the first match of a regular expression in the input string beginning at the specified start index.
The prototype of the find function is as follows:
fun find(input: CharSequence, startIndex: Int = 0): MatchResult?
The following example program will demonstrate the usage of the find function.
// Kotlin program to demonstrate regex find function
fun main(){
val regex = "\\d+".toRegex()
val input_str = "Welcome to Coding Ninjas 2022. Achieve your dream in 100 days"
println(regex.find(input_str)?.value) // There are two substrings that match the given input regex
// The first one is 2022 and second is 100
// The find function returns the first one
// Since the startIndex is not specified the default value zero has been taken.
}
Output
2022
matchAt
This function is used to match a regular expression at an index specified in the input string.
The prototype of the matchAt function is as follows.
fun matchAt(input: CharSequence, index: Int): MatchResult?
The following program demonstrates the usage of matchAt function.
// Kotlin program to demonstrate regex matchAt function
@kotlin.ExperimentalStdlibApi
fun main(){
val regex = "\\d+".toRegex()
val input_str = "Welcome to Coding Ninjas 2022"
// Indexing is zero based
println(regex.matchAt(input_str, 0)) // Matching from position 0
println(regex.matchAt(input_str, 25)?.value) // Matching from position 25
}
Output:
null
2022
matches
This function checks whether a given input string matches a regular expression or not.
The prototype of the matches function is as follows.
infix fun matches(input: CharSequence): Boolean
The following program demonstrates the usage of matches function.
// Kotlin program to demonstrate regex matches function
fun main(){
val regex = """a([12]+)e?""".toRegex()
val match_1 = regex.matches(input = "ae")
val match_2 = regex.matches(input = "1abcd34e")
val match_3 = regex.matches(input = "a1e")
val match_4 = regex.matches(input = "a121e")
println("Match 1 value: " + match_1)
println("Match 2 value: " + match_2)
println("Match 3 value: " + match_3)
println("Match 4 value: " + match_4)
}
Output:
Match 1 value: false
Match 2 value: false
Match 3 value: true
Match 4 value: true
replace
This function replaces all occurrences of the regular expression in the input string with the replacement expression that is supplied as input to this function.
The prototype of the replace function is as follows:
fun replace(input: CharSequence, replacement: String): String
The following program demonstrates the use of replace function.
// Kotlin program to demonstrate regex replace function
fun main(){
val regex = Regex("""students""")
var input_str: String = "Only students are allowed"
println("Original String: " + input_str)
input_str = regex.replace(input_str, "ninjas")
println("Updated String: " + input_str)
}
Output:
Original String: Only students are allowed
Updated String: Only ninjas are allowed
replaceFirst
This function replaces the first occurrences of the regular expression in the input string with the replacement expression that is supplied as input to this function.
The prototype of the replaceFirst function is as follows:
fun replaceFirst(input: CharSequence, replacement: String): String
The following program demonstrates the use of replaceFirst function.
// Kotlin program to demonstrate regex replaceFirst function
fun main(){
val regex = Regex("""students""")
var input_str: String = "Only students and ex-students are allowed"
println("Original String: " + input_str)
input_str = regex.replaceFirst(input_str, "ninjas")
println("Updated String: " + input_str)
}
Output:
Original String: Only students and ex-students are allowed
Updated String: Only ninjas and ex-students are allowed
split
This function splits the supplied character sequence into a list of strings based on regular expression matching.
The prototype of the split function is as follows:
fun split(input: char_sequence, limit: Int = 0): List<String>
The parameter limit specifies the maximum number of substrings the string can be split into. The default value is set to zero, which means no limit is set.
The following example program will demonstrate the usage of the split function.
// Kotlin program to demonstrate regex split function
fun main(){
// Method 1 using Regex
val split_res: List<String> = Regex("""\s+""").split("Welcome to Coding Ninjas")
println("Method 1: " + split_res)
// Method 2 using toRegex()
val regex_exp = """\d+"""
val regex = regex_exp.toRegex()
val input_str = "Ninjas123are321Coding"
val split_res_2: List<String> = regex.split(input_str)
println("Method 2: " + split_res_2)
}
Output:
Method 1: [Welcome, to, Coding, Ninjas]
Method 2: [Ninjas, are, Coding]
toPattern
This function is used to convert our Kotlin regex into a Java pattern. It is especially useful when we need to pass our regular expression to an API that expects an instance of java.util.regex.Pattern.
The prototype of the toPattern function is as follows.
fun toPattern(): Pattern
The toPattern function is invoked as follows.
regex.toPattern()
toString
This function is used to get the string representation of the given regular expression.
The prototype of the toString function is as follows.
fun toString(): String
Must Read Elvis Operator Kotlin
FAQs
-
What does a * denote in regex?
A regular expression followed by the character * denotes zero or positive occurrences of the regular expression.
-
Why are \\ generally used in regular expressions?
\\ is used to denote a single backslash in a regular expression. It is a convention of telling that the given backslash does not denote the end of the string.
-
What is the need/requirement of regular expressions?
Regular expressions are generally useful where search and replace operations need to be performed. Regex can be used to find a substring that matches a given pattern.
Key Takeaways
Cheers if you reached here!! The purpose of this blog was to introduce you to the regular expressions support in Kotlin standard library. To read about reflection in Kotlin, go ahead and read the blog Kotlin Reflection on the Coding Ninjas website.
Yet there is never an end to the learning process, so check out our Android Development Course on the Coding Ninjas Website to learn everything you need to know about Android development and how to design future applications. Until then, good luck!!