To replace a substring in a string using regular expression in Kotlin, you can utilize the replace
function with a regex pattern.
In this example,
str
.replace
function on str
with a regex pattern matching "Hello" and replace it with "Hi".replace
function returns a new string with the replacements made.fun main() {
val str = "Hello World Hello"
val newStr = str.replace("Hello", "Hi")
println(newStr)
}
Hi World Hi
In this example,
str
.replace
function on str
with a regex pattern matching digits (\d) and replace them with 'Y'.replace
function returns a new string with the replacements made.fun main() {
val str = "Hello123World789"
val newStr = str.replace(Regex("\\d"), "Y")
println(newStr)
}
HelloYYYWorldYYY
In this tutorial, we learned How to Replace a Substring in a String using Regular Expression in Kotlin language with well detailed examples.