Industrial Training




Kotlin Regex


Regex is generally refers to regular expression which is used to search string or replace on regex object. To use it functionality we need to use Regex(pattern: String) class. Kotlin'sRegex class is found in kotlin.text.regex package.


Kotlin Regex Constructor

>
Regex(pattern: String) It creates a regular expression from the given string pattern.
Regex(pattern: String, option: RegexOption) It creates a regular expression from the given string pattern and given single option.
Regex(pattern: String, options: Set< RegexOption>) It creates a regular expression from the given string pattern and set of given options.

Regex Functions


Functions Descriptions
fun containsMatchIn(input: CharSequence): Boolean It indicates that regular expression contains at least one input character
fun find( input: CharSequence, startIndex: Int = 0 ): MatchResult? It returns the first match of regular expression in the input character sequence, begins from given startIndex.
fun findAll( input: CharSequence, startIndex: Int = 0 ): Sequence< MatchResult> It returns all occurrences of regular expression in the input string, starts from the given startIndex.
funmatchEntire(input: CharSequence): MatchResult? It is used to match complete input character from the pattern.
infix fun matches(input: CharSequence): Boolean It indicates whether all input character sequence matches in regular expression.
fun replace(input: CharSequence, replacement: String): String It replaces all the input character sequence of regular expression with given replacement string.
fun replaceFirst( input: CharSequence, replacement: String ): String It replaces the first occurrence of regular expression in the given input string with given replacement string.
fun split(input: CharSequence, limit: Int = 0): List< String> It splits the input character sequence of regular expression.
fun toPattern(): Pattern fun toString(): String It returns the regular expression in string.

Example of Regex class checking contains of input pattern


fun main(args: Array){  
val regex = Regex(pattern = "ko")  
val matched = regex.containsMatchIn(input = "kotlin")  
println(matched)  
}  

Output:
true

The result of Regex function is based on matching regex pattern and the input string. Some function checks partial match while some checks full match.


Regex example of containsMatchIn()


fun main(args: Array){  
  
val regex = """a([bc]+)d?""".toRegex()  
val matched = regex.containsMatchIn(input = "xabcdy")  
println(matched)  
  
}  

Output:
true

Regex example of matches(input: CharSequence): Boolean


The matches(input: CharSequence): Booleanfunction of regex checksall input character sequence matches in regular expression.


fun main(args: Array< String>){  
  
val regex = """a([bc]+)d?""".toRegex()  
val matched1 = regex.matches(input = "xabcdy")  
val matched2 = regex.matches(input = "xabcdyabcd")  
val matched3 = regex.matches(input = "abcd")  
println(matched1)  
println(matched2)  
println(matched3)  
}  

Output:
false
false
true

Regex example of matchEntire(input: CharSequence): MatchResult?


The matchEntire() function is used to match complete input character from the pattern.


fun main(args: Array){  
  
val regex = Regex("abcd")  
val matchResult1 = regex.matchEntire("abcd")?.value  
val matchResult2 = regex.matchEntire("abcda")?.value  
  
val matchResult3 = Regex("""\d+""").matchEntire("100")?.value    
val matchResult4 = Regex("""\d+""").matchEntire("100 dollars")?.value  
  
println(matchResult1)  
println(matchResult2)  
println(matchResult3)  
println(matchResult4)  
}  

Output:
abcd
null
100
null

Regex example offind(input: CharSequence, startIndex: Int = 0): MatchResult?


The find function is used to find the input character sequence from regex object.


fun main(args: Array){  
  
val emailParttern = Regex("""\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6}""")  
val email :String? = emailParttern.find("this is my email mymail@google.com")?.value  
println(email)  
val phoneNumber :String? = Regex(pattern = """\d{3}-\d{3}-\d{4}""")  
            .find("phone: 123-456-7890, e..")?.value   
println(phoneNumber)  
}  

Output:
mymail@google.com
123-456-7890

Regex example offindAll(input: CharSequence, startIndex: Int = 0): Sequence< MatchResult>


The findAll() function of regex returns sequence of match result on the basis of pattern provided.


fun main(args: Array< String>){  
val foundResults = Regex("""\d+""").findAll("ab12cd34ef 56gh7 8i")  
val result = StringBuilder()  
    for (findText in foundResults) {  
result.append(findText.value + " ")  
    }  
println(result)  
}  

Output:
12 34 56 7 8

Regex example ofreplace(input: CharSequence, replacement: String): String


Regex replace() function replaces the all the matching pattern from input character sequence with specified replacement string.


fun main(args: Array){  
val replaceWith = Regex("beautiful")  
val resultString = replaceWith.replace("this picture is beautiful","awesome")  
println(resultString)  
}  

Output:
this picture is awesome

Regex example ofreplaceFirst(input: CharSequence, replacement: String): String


Regex replaceFirst() function replaces the first occurrence of matching pattern from input character sequence with specified replacement string.


fun main(args: Array< String>){  
val replaceWith = Regex("beautiful")  
val resultString = replaceWith.replaceFirst("nature is beautiful, beautiful is nature","awesome")  
println(resultString)  
}  

Output:
nature is awesome, beautiful is nature

Regex example ofsplit(input: CharSequence, limit: Int = 0): List< String>


The regex split() function splits input character sequence according to pattern provided. This splits value are returned in List.


fun main(args: Array){  
val splitedValue = Regex("""\d+""").split("ab12cd34ef")  
val nonsplited= Regex("""\d+""").split("nothing match to split" )  
println(splitedValue)  
println(nonsplited)  
}  

Output:
[ab, cd, ef]
[nothing match to split]



Hi I am Pluto.