Contents
Regex & Ranges
Regular Expression
Kotlin provides robust support for regular expressions through the Regex
class, which allows for efficient string pattern matching. A Regex
object represents a regular expression and can be used for various string-matching purposes.
Constructors:
- Regex(pattern: String): Creates a regular expression from the provided pattern.
- Regex(pattern: String, option: RegexOption): Creates a regular expression with a specific option from the RegexOption enum.
- Regex(pattern: String, options: Set<RegexOption>): Creates a regular expression with a set of options.
Properties:
- val options: Set<RegexOption>: Contains the set of options used for regex creation.
- val pattern: String: Stores the pattern as a string.
Functions in Regex
1. containsMatchIn(): This function checks if there is a match for the regex pattern within a given input and returns a boolean.
fun main() {
val pattern = Regex("^a") // Matches any string starting with 'a'
println(pattern.containsMatchIn("abc")) // true
println(pattern.containsMatchIn("bac")) // false
}
Output:
fun main() {
val pattern = Regex("^a") // Matches any string starting with 'a'
println(pattern.containsMatchIn("abc")) // true
println(pattern.containsMatchIn("bac")) // false
}
2. find(): This function returns the first match of the regex in the input starting from a specified index.
fun main() {
val pattern = Regex("ll") // Matches "ll"
val match: MatchResult? = pattern.find("HelloHello", 5)
println(match?.value) // ll
}
Output:
ll
3. findAll() : This function finds all the matches for a regex in the input starting from a specified index and returns them as a sequence.
fun main() {
val pattern = Regex("ab.")
val matches: Sequence = pattern.findAll("abcabdeabf", 0)
matches.forEach { match -> println(match.value) }
}
Output:
abc
abd
4. matches(): This function checks if the entire input string matches the regular expression.
fun main() {
val pattern = Regex("g([ee]+)ks?")
println(pattern.matches("geeks")) // true
println(pattern.matches("geeeeeeks")) // true
println(pattern.matches("geeksforgeeks")) // false
}
Output:
true
true
false
5. matchEntire(): This function tries to match the entire input string to the regex pattern and returns the match if successful, otherwise returnsnull
.
fun main() {
val pattern = Regex("geeks?")
println(pattern.matchEntire("geeks")?.value) // geeks
println(pattern.matchEntire("geeeeeks")?.value) // null
}
Output:
geeks
null
6. replace(): This function replaces all occurrences of the pattern in the input string with a replacement string.
7.replaceFirst()
: Replaces only the first occurrence.
fun main() {
val pattern = Regex("xyz")
println(pattern.replace("xyzxyz", "abc")) // abcabc
println(pattern.replaceFirst("xyzxyz", "abc")) // abcxyz
}
Output:
abcabc
abcxyz
8. split(): This function splits the input string into parts based on the regular expression pattern.
fun main() {
val pattern = Regex("\\s+") // Split by whitespace
val result = pattern.split("Kotlin is great")
result.forEach { println(it) }
}
Output:
Kotlin
is
great
Ranges
In Kotlin, a range is a collection of values defined by a start point, an end point, and a step. The range includes both the start and stop values, and the step value, which is the increment or decrement, is 1 by default. Kotlin’s range can work with comparable types like numbers and characters.
Creating Ranges in Kotlin
There are three primary ways to create a range:
1. Using the .. operator
2. Using the rangeTo() function
3. Using the downTo() function
1. Using the ..
Operator: The ..
operator creates a range from the start to the end value, including both.
Example 1: Integer Range
fun main() {
println("Integer range:")
for (num in 1..5) {
println(num)
}
}
Output:
Integer range:
1
2
3
4
5
Example 2: Character Range
fun main() {
println("Character range:")
for (ch in 'a'..'e') {
println(ch)
}
}
Output:
Character range:
a
b
c
d
e
2. Using the rangeTo()
Function : The rangeTo()
function is another way to create ranges, similar to using the ..
operator.
Example 1: Integer Range
fun main() {
println("Integer range:")
for (num in 1.rangeTo(5)) {
println(num)
}
}
Output:
Integer range:
1
2
3
4
5
Example 2: Character Range
fun main() {
println("Character range:")
for (ch in 'a'.rangeTo('e')) {
println(ch)
}
}
Output:
Character range:
a
b
c
d
e
3. Using the downTo()
Function: The downTo()
function creates a range that decreases from the starting value to the ending value.
Example 1: Integer Range in Descending Order
fun main() {
println("Integer range in descending order:")
for (num in 5.downTo(1)) {
println(num)
}
}
Output:
Integer range in descending order:
5
4
3
2
1
Example 2: Character Range in Descending Order
fun main() {
println("Character range in reverse order:")
for (ch in 'e'.downTo('a')) {
println(ch)
}
}
Output:
Character range in reverse order:
e
d
c
b
a
Using the forEach
Loop
The forEach
loop can also be used to traverse over a range.
fun main() {
println("Integer range:")
(2..5).forEach(::println)
}
Output:
Integer range:
2
3
4
5
step(): Customizing the Increment:
The step()
function allows you to specify the increment or step value in the range. By default, the step value is 1.
Example: Step Usage
fun main() {
// Custom step value
for (i in 3..10 step 2) {
print("$i ")
}
println()
println((11..20 step 2).first) // Print first value
println((11..20 step 4).last) // Print last value
println((11..20 step 5).step) // Print step value
}
Output:
3 5 7 9
11
19
5
reversed(): Reversing the Range:
The reversed()
function reverses the range.
fun main() {
val range = 2..8
for (x in range.reversed()) {
print("$x ")
}
}
Output:
8 7 6 5 4 3 2
Predefined Functions for Ranges
Kotlin offers predefined functions like min()
, max()
, sum()
, and average()
to work with ranges.
fun main() {
val predefined = (15..20)
println("The minimum value of range is: ${predefined.minOrNull()}")
println("The maximum value of range is: ${predefined.maxOrNull()}")
println("The sum of all values of range is: ${predefined.sum()}")
println("The average value of range is: ${predefined.average()}")
}
Output:
The minimum value of range is: 15
The maximum value of range is: 20
The sum of all values of range is: 105
The average value of range is: 17.5
Checking if a Value Lies in a Range
You can check if a value lies within a range using the in
keyword.
fun main() {
val i = 2
if (i in 5..10) {
println("$i lies within the range")
} else {
println("$i does not lie within the range")
}
}
Output:
2 does not lie within the range