1

If I have a string representation of list s = '["a", "b", "c"]', how do I parse this string to extract the list object? Expected output l = ["a", "b", "c"]

Shirley Du
  • 45
  • 8

1 Answers1

3
val str = """["a","b" "c"]"""    // string with quote marks
val getStrs = "\"([^, ]+)\"".r   // regex to isolate quoted strings

Now to pull those quoted strings (without the quote marks) into a List[String].

val lst = (for (m <- getStrs findAllMatchIn str) yield m group 1).toList
// lst: List[String] = List(a, b, c)
jwvh
  • 50,871
  • 7
  • 38
  • 64
  • Thank you! Would it be possible to parse a list of jsons? E.g., `str="""[{"index": 1}, {"index": 2}]"""` and expected lst to be `[{"index": 1}, {"index": 2}]` ? – Shirley Du Sep 22 '16 at 01:28
  • To work with JSON you should probably use JSON tools. You might [start here](http://stackoverflow.com/questions/8054018/what-json-library-to-use-in-scala). – jwvh Sep 22 '16 at 01:45
  • Oh sorry that's not what I meant. I mean if the list is a list of JSONs, then the delimiter would be a bit different since there would be commas inside the JSON string as well. I'm not sure if it's possible to to parse this list the example commented above by using regular expressions. Any help is greatly appreciated! @jwvh – Shirley Du Sep 22 '16 at 01:56
  • 1
    I see three issues here. 1) It's hard to know exactly what you're after because the stated expected output isn't meaningful Scala. 2) JSON elements can be complicated (nested elements, etc.). Is your example input the only type of JSON element to be parsed? 3) This is a different question, worthy of a new/different posting. That way you're likely to get more eyes on it and better responses. – jwvh Sep 22 '16 at 02:28
  • Actually I just resolved it. It's pretty simple. The list of JSONs is actually a valid JSON, so I could just use the built-in library. But thanks still!! – Shirley Du Sep 22 '16 at 02:46
  • Excellent! Glad to hear it. Sounds like I might have been right about using JSON tools to tackle JSON strings. – jwvh Sep 22 '16 at 03:16