How to convert a multiline Scala multiline String to an Array (or Seq)

Scala string FAQ: How do I convert a multiline String to an Array or Seq or List in Scala?

I was just working on a program to parse Apache access log records, and ran into this situation. Here’s the solution.

Given a multiline Scala string, like this:

  val data = """ - - [21/Jul/2009:02:48:11 -0700] "GET /foo HTTP/1.1" 200 16731 "" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/2009060215 Firefox/3.0.11 GTB5" - - [21/Jul/2009:02:48:12 -0700] "GET /favicon.ico HTTP/1.1" 404 970 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv: Gecko/2009060215 Firefox/3.0.11" - - [21/Jul/2009:02:48:13 -0700] "GET / HTTP/1.1" 200 18209 "" "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"

you can convert that string to an array like this:

val arr = data.split("\n")

In my case I also wanted/needed to weed out the empty strings, so I added a filter method call after split:

val arr = data.split("\n").filter(_ != "")

That’s all you need to do to convert a string to an array in Scala. If you want to be more specific and get a Seq, List, or other type as the result of these calls, just call one of the to* methods that are available on the resulting array (toSeq, toList, etc.).