How to replace consecutive characters with only one using RegEx in Scala

1 Answer

0 votes
import scala.util.matching.Regex

object RemoveConsecutiveDuplicates {
  def removeConsecutiveDuplicates(input: String): String = {
    // Matches any character (.) followed by itself one or more times (\1+)
    val pattern: Regex = "(.)\\1+".r

    // Replaces with the first captured group
    pattern.replaceAllIn(input, "$1")
  }

  def main(args: Array[String]): Unit = {
    val input = "aaaabbbccdddddd"
    val modified = removeConsecutiveDuplicates(input)

    println(s"Original: $input")
    println(s"Modified: $modified")
  }
}


 
/*
run:

Original: aaaabbbccdddddd
Modified: abcd

*/

 



answered Jun 7 by avibootz
...