Updated April 5, 2023
Introduction to Kotlin Regex
Kotlin regex is one of the types of a fundamental part of the programming language and it supports the regex is the class that represents the object for the regular expression that can be used for matching the string values it also uses the other constructors which will accept both parameters and non-parameters and it accepts other default and non-default methods the string datatype and other operators used by these classes and its methods for utilizing the text searches and advanced development contents the pattern expression defines the text and it comprises the text literals and metacharacters.
Syntax of Kotlin Regex
In kotlin language the regular expression is mainly used to find and search the text in the html contents and it provides the Regex() class to deal with the other default functions. It has many operators, operands, and other symbols to perform the operations in the kotlin application.
fun main(args:Array<String>)
{
val vars1="values".toRegex()
val vars2="values1"
val res=regex.replace(vars2,"new")
val match=regex.matches("values")?.value
----some logic codes depends on the requirement---
}
The above codes are the basic syntax for to utilizing the regular expression in the specified strings with the operands and operators like special characters and symbols.
How does Regex work in Kotlin?
The kotlin regex() is like methods and the class which is used to write the expression and validate the text datas, searching and advanced content for the development purposes. Most probably it can be supported all the characters like both alphabets and non-alphabets, symbols, and operators. The regular expression is primarily used to find and search the text in the contents and deal with a regular expression and kotlin provides the Regex() class its functions handled these types of expressions. It has some types like pattern regular expression that can be characterized with the content and for looking or controlling it comprises the text literals and metacharacters.
The metacharacters are one of the special characters that can be controlled using the regular expression will be assessed. Kotlin regular expression has some default methods like replace(), replaceFirst(), matches() etc. These are some default methods that performed the operations using the specified tasks. Additionally the operators like “.” are used to match any type of single sting value ,”+” is for matching the preceding element with one or more times. Like that other symbols like “*” is used to match with preceding element with zero or more number of times “^” is matched at the starting position of the string, “$” is at the ending position. We used a lot of operators like “?, |,\s,\w,[abc],[^abc],[a-c], etc these are the various pattern regular expressions that can be used to match the pattern in the variable outputs.
Examples of Kotlin Regex
Given below are the examples mentioned:
Example #1
Code:
import java.util.Scanner;
fun firstExample(num1: Int, str2: String) {
num1.takeIf{it >= 0 }?.let {
println("Welcome User Integer is the first input and string type is the second input.")
println("$it.")
}
}
fun main()
{
val ptn = Regex("^b")
println(ptn.containsMatchIn("abc"))
println(ptn.containsMatchIn("bac"))
println("Welcome To My Domain its the first example related to the kotlin regex expression")
println("#############################################################")
val q = arrayOf(8,2,4)
q.forEach { num -> println(num * num) }
q.forEach { println(it*it) }
var s1 = Scanner(System.`in`)
print("Please enter your Jewellery Shop:")
var jshop = s1.nextInt()
var out = when(jshop){
1->"Saravana Gold"
2->"Saravana Thanga Malligai"
3->"Bharani Silver"
4->"Kumaran Thanga malligai"
5->"jk jewelley"
6->"pks jewellery"
7->"raj jewellery"
8->"kumar jewellery"
9->"lalitha jewellery"
10->"GRT gold jewellery"
11->"The Legend Saravana Jewellery Shop"
12->"Saradha Jewellery"
13->"Del Jewellery"
14->"SPJ Jewellery"
15->"JUY Jewellery"
else -> {
println("Your brand is not listed here")
}
}
println(out)
val inp1 = HashMap<String, String>()
inp1["Model Name"] = "Dell Inspiron"
inp1["Model Price"] = "35000"
inp1["Model ID"] = "45632"
for ((k, v) in inp1) {
println("Thank you users your inputs are $k = $v")
}
val inp2 = mapOf("Model Name" to "HP", "Model Price" to 54000, "Model ID" to 89765)
println("Your input Keys are:" + inp2.keys)
println("Your input Values are:" + inp2.values)
println("Thank you users have a nice day please keep and spent time with our application")
firstExample(41, "Siva")
firstExample(44, "Raman")
}
Output:
In the above example, we used the collection concept to perform the data operations with included the regular expression.
Example #2
Code:
enum class pc(val x: Boolean = true){
Sony,
Dell,
Lenovo,
Apple,
Wipro,
HCL;
companion object{
fun pcdetails(obj: pc): Boolean {
return obj.name.compareTo("Sony") == 0 || obj.name.compareTo("Apple") == 0
}
}
}
fun compdetails(comp: pc) {
when(comp) {
pc.Sony -> println("Sony")
pc.Dell -> println("Dell")
pc.Lenovo -> println("Lenovo")
pc.Apple -> println("Apple")
pc.Wipro -> println("Wipro")
pc.HCL ->println("HCL")
}
}
fun main() {
val urptn = "[a-zA-Z0-9]+"
val fr = Regex(urptn)
println(fr.matches("Siva_Raman"))
println(fr matches "Siva_Raman")
println(fr.matches("Siva_Raman"))
val inp1 = Regex("ab.")
val res : Sequence<MatchResult> = inp1.findAll("awerbc653ksjnj", 1)
res.forEach()
{
out -> println(out.value)
}
println(res)
var ptn = Regex("Welcome To My Domain its the second example that related to the kotlin regex expression?")
println(ptn.matchEntire("Welcome To My Domain its the second example that related to the kotlin regex expression")?.value)
println(ptn.matchEntire("Users Have a Nice Day")?.value)
ptn = Regex("""\D+""")
println(ptn.matchEntire("Welcome To My Domain its the second example that related to the kotlin regex expression")?.value)
println(ptn.matchEntire("Please spent the time with us")?.value)
val uptn = "[a-zA-Z0-9]+"
val sec = Regex(uptn)
println(sec.containsMatchIn("Siva_Raman is the SOftware Support Engineer and it works in XYZ Company"))
println(sec.containsMatchIn("!#$%"))
}
Output:
In the second example, we used enum, companion object additionally with the regular expression tasks.
Example #3
Code:
fun main() {
val inp1 = listOf("Tamil", "English", "Physics",
"Chemistry","Biology", "ComputerScience", "Engineering Graphics")
val ptn = "Tamil".toRegex()
println("*********************")
println("Welcome To My Domain its the Third Example that related to the Kotlin RegEx expression")
println("We used the other default regular expression method like ContainsMatchIn function")
inp1.forEach { ls ->
if (ptn.containsMatchIn(ls)) {
println("$ls matches")
}
}
println("*********************")
println("Like that we used the Regular Expression matches function")
inp1.forEach { ls ->
if (ptn.matches(ls)) {
println("Your input datas are matched and see below results : $ls matches")
}
}
}
Output:
In the final example, we used other pre-defined regular expression methods like matches and patterns to perform the user input operations.
Conclusion
In kotlin language, we used a lot of default methods, keywords, and variables to perform the operations in an application. Like that the application task varies depends upon the requirement among that regular expression is to find the string values and matches or compare with the same path or different path of the variable memory location.
Recommended Articles
This is a guide to Kotlin Regex. Here we discuss the introduction, syntax, and working of regex in Kotlin along with different examples for better understanding. You may also have a look at the following articles to learn more –