How to remove parentheses and the text inside them from a string in Scala

1 Answer

0 votes
/**
 * Remove all parentheses and the text inside them.
 *
 * @param text  The input string
 * @return      The cleaned string
 */
def removeParenthesesWithContent(text: String): String = {
  // Remove parentheses and everything inside them
  val cleaned: String = text.replaceAll("\\([^)]*\\)", " ")

  // Collapse multiple spaces into one
  val collapsed: String = cleaned.split("\\s+").mkString(" ")

  // Final trim of leading/trailing spaces
  collapsed.trim
}

@main def run(): Unit = {
  val str: String =
    "(An) API (API) (is a) (connection) connects (between) computer programs"

  val output: String = removeParenthesesWithContent(str)

  println(output)
}


/*
run:

API connects computer programs

*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz

Related questions

...