Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace duplicated string using re{n,} in Kotlin?

Tags:

kotlin

I want change "aaa" or "aa..." to "." using Regex(re{2,})

Below is my code

    var answer = "aaa"
    var re = Regex("re{2,}a") // Regex("are{2,}")
    answer = re.replace(answer,".")
    println(answer)

Regex("re{2,}a") and Regex("are{2,}")

Both println aaa

How can I replace duplicated string using re{n,} ??

like image 637
helloworld Avatar asked Dec 12 '25 12:12

helloworld


2 Answers

Generic regex to replace any duplicates (not only duplicate a symbols) is (?<symbol>.)\k<symbol>+

You may define an extension function for convenient usage:

private val duplicateRegex = "(?<symbol>.)\\k<symbol>+".toRegex()
fun String.replaceDuplicatesWith(replacement: String): String = replace(duplicateRegex, replacement)

Usage:

println("a".replaceDuplicatesWith("."))     //a
println("aaa".replaceDuplicatesWith("."))   //.
println("aa...".replaceDuplicatesWith(".")) //..

If you want duplicates to be iteratively replaced (like "aa..." -> ".." -> ".") you'll need an auxilary recursive method:

tailrec fun String.iterativelyReplaceDuplicatesWith(replacement: String): String {
    val result = this.replaceDuplicatesWith(replacement)
    return if (result == this) result else result.iterativelyReplaceDuplicatesWith(replacement)
}

Usage:

println("a".iterativelyReplaceDuplicatesWith("."))     //a
println("aaa".iterativelyReplaceDuplicatesWith("."))   //.
println("aa...".iterativelyReplaceDuplicatesWith(".")) //.
like image 174
Михаил Нафталь Avatar answered Dec 15 '25 04:12

Михаил Нафталь


fun main(args: Array<String>) {
    var tests = arrayOf("a","aa","aaa","aaaa")
    val re = Regex("a(a+)")
    tests.forEach {t->
        val result = re.replace(t,".")
        println(result)
    }
}

output:

a . . .

like image 36
Naor Tedgi Avatar answered Dec 15 '25 04:12

Naor Tedgi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!