Scala — Parsing strings with pattern matching
Scala pattern matching can unpack a two-element array after a split. Limiting the split to two keeps any later separators inside the value.
A simple example
Split one line of text
- Start with "a=b"
- Do this Separate at =
- Result b
object Lesson extends App {
val parts = "a=b".split("=")
println(parts(1))
}
b
Split one setting into a key and a value
The positive split limit keeps later separators in the value. Array(key, value) matches only a two-element array. The fallback handles a missing separator.
A noticeboard reads its city from a saved setting. Split the line at its first equals sign and trim the spaces around the two fields. The board can now look up city and display Lima.
Run the example
Scala 2.13 with JDK 11 or later. Run these commands from the directory containing the example.
scalac Lesson.scala
scala Lesson
object Lesson {
def main(args: Array[String]): Unit = {
val record = " city = Lima "
record.split("=", 2) match {
case Array(key, value) => println(key.trim + "=" + value.trim)
case _ => println("missing separator")
}
}
}
city=Lima
The input contains padding around city and Lima. Locating the first separator identifies the two fields. Trimming their ends gives city=Lima without changing text inside the value.
Try it yourself
What should city = A=B produce?
Check your answer
The value retains its second equals sign. The normalized line is city=A=B. Decide separately whether an empty key is valid for your file format.