Kotlin Regular Expression

12. Kotlin Regular Expression 12.1 Regex() Class 12.2 Pattern Regular Expression 12.3 Regex() functions


Regex() Class

The regular expression is used to find or search text in a content. To deal with regular expression, kotlin provides Regex() class, that has many functions to deal with regular expressions in kotlin.

Syntax

Regex(pattern: String, option: RegexOption)

In the above syntax, string is the input type and pattern is the regular expression that defines the text we are looking for. The option parameter is optional that contains a single option.

Example

var r = Regex(pattern: x)

Pattern Regular Expression

Regex Matching
. to match any single string
+ to match the preceding element once or more times
* to match the preceding element zero or more times
^ to match the starting position of a string
$ to match the ending position of a string
? to match preceding element only once.
| or operator
[abc] to match within a, or b, or c
[^abc] to match except a, or b, or c
[a-c] to match in range a to c
\s to match white space character
\w to match a word character




Regex() functions

Kotlin find() method

It returns the first match substring of a regular expression, beginning at the specified start index. The start index is 0 by default.

fun main(args : Array<String>)  { 
	val regex = """(abcd|efgh)""".toRegex()
    val match = regex.find("abc fg")
}

Kotlin findAll() method

It returns all possible matching substrings of a regular expression, beginning at the specified start index.

fun main(args : Array<String>)  { 
	val regex = """(abcd|efgh)""".toRegex()
	val match = regex.findAll("abc")
}

Kotlin matchEntire() method

It is used to match the entire character of a regular expression.

fun main(args : Array<String>)  { 
	val regex = """(abcd|efgh)""".toRegex()  
	val match = regex.matchEntire("abcd")?.value  
}

Kotlin matches() method

It is a boolean function that checks all the matched input character sequence in a regular expression.

fun main(args : Array<String>)  { 
	val regex = """(abcd|efgh)""".toRegex()  
	val match = regex.matches("abcd")?.value  
}

Kotlin replace() method

It replaces all occurrences of the regular expression in the specified input string.

fun main(args : Array<String>)  { 
	val regex = """(east|west)""".toRegex()
	val zone = "Table is in east zone, chair is in west zone."  
	val newzone = regex.replace(zone, "center")
	println(newzone)
}
Output
Table is in center zone, chair is in center zone.

Kotlin replaceFirst() method

It replaces only the first occurrence of the regular expression in the specified input string.

fun main(args : Array<String>)  { 
	val regex = """(east|west)""".toRegex()
	val zone = "Table is in east zone, chair is in west zone."  
	val newzone = regex.replaceFirst(zone, "center")
	println(newzone)
}
Output
Table is in center zone, chair is in west zone.







Read more articles


General Knowledge



Learn Popular Language