3

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,} ??

1
  • What means "aa..." to "."? You want any duplicate character to be replaced with ".", and it should be done iteratively until there will be no duplicatres? Like on 1st iteration "aa" is replaced with "." and "..." is replaced with ".", so result of iteration is "..", which is afterwards replaced with "."? Or aa... is just a notation for bunch of a characters? Commented Apr 12, 2021 at 12:21

2 Answers 2

2

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(".")) //.
Sign up to request clarification or add additional context in comments.

Comments

1
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 . . .

4 Comments

thank you! Umm.. then if i want to . to a how can I do that? . mean all character...
ah using //. I got it
not sure i understand you ? did the problem solve?
great! so please mark the question as solved

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.