scalabeginner

String Processing and Regex

Process strings with Scala regex, interpolation, pattern matching extractors, and common operations.

scala
import scala.util.matching.Regex

@main def run(): Unit =
  val text = "Hello, World! This is Scala 3."

  // Basic operations
  println(text.toUpperCase)
  println(text.toLowerCase)
  println(text.reverse)
  println(text.take(5))       // Hello
  println(text.drop(7))       // World! This is Scala 3.
  println(text.contains("Scala"))
  println(text.startsWith("Hello"))

  // Split and join
  val csv = "alice,30,engineer,NYC"
  val parts = csv.split(",")
  println(parts.mkString(" | "))

  // Regex
  val emailRegex = """([\w.+-]+)@([\w-]+\.\w+)""".r
  val emails = "Contact alice@test.com or bob@example.org"

  emailRegex.findAllIn(emails).foreach(println)

  // Regex extraction with pattern matching
  "alice@test.com" match
    case emailRegex(user, domain) =>
      println(s"User: $user, Domain: $domain")
    case _ => println("Not an email")

  // Find all matches with groups
  val logLine = "2024-01-15 10:30:45 ERROR [main] Connection failed"
  val logRegex = """(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) (\w+) \[(\w+)\] (.+)""".r
  logLine match
    case logRegex(date, time, level, thread, msg) =>
      println(s"Date: $date, Time: $time, Level: $level")
      println(s"Thread: $thread, Message: $msg")
    case _ => println("Not a log line")

  // Replace with regex
  val cleaned = "Hello   World   Foo".replaceAll("\\s+", " ")
  println(cleaned)

  // Strip margin for multi-line
  val sql = s"""
    |SELECT name, age
    |FROM users
    |WHERE age > 18
    |ORDER BY name
    """.stripMargin.trim
  println(sql)

  // String builder
  val sb = StringBuilder()
  for i <- 1 to 5 do
    sb.append(s"Item $i")
    if i < 5 then sb.append(", ")
  println(sb.result())

  // Char operations
  val digits = "abc123def456".filter(_.isDigit)
  val letters = "abc123def456".filter(_.isLetter)
  println(s"Digits: $digits, Letters: $letters")

Use Cases

  • Text parsing and extraction
  • Log file processing
  • Input validation with regex

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.