How to remove all non-numeric characters from a string in Scala

1 Answer

0 votes
object NumericExtractor {

  /**
   * Removes all non-numeric characters from a string, returning a new string
   * containing only numeric digits (0-9).
   * 
   * @param input The source string containing alphanumeric and special characters.
   * @return A new String containing only digits.
   * @throws IllegalArgumentException if the input string is null.
   */
  def removeNonNumeric(input: String): String = {
    // Guard clause: input cannot be null
    require(input != null, "Input string cannot be null.")

    // Filter the characters keeping only digits using Scala's built-in isDigit method
    input.filter(_.isDigit)
  }

  def main(args: Array[String]): Unit = {
    // Test string provided
    val text = "123XYZ +9982-programming 10000000000001language"
    
    // Process the string
    val cleanedText = removeNonNumeric(text)

    // Output results
    println(s"Original: $text")
    println(s"Cleaned:  $cleanedText")
  }
}


/*
run:

Original: 123XYZ +9982-programming 10000000000001language
Cleaned:  123998210000000000001

*/

 



answered 13 hours ago by avibootz

Related questions

...