Jack
Jack

Reputation: 16718

Select substring between two characters in Scala

I'm getting a garbled JSON string from a HTTP request, so I'm looking for a temp solution to select the JSON string only.

The request.params() returns this:

[{"insured_initials":"Tt","insured_surname":"Test"}=, _=1329793147757,
callback=jQuery1707229194729661704_1329793018352

I would like everything from the start of the '{' to the end of the '}'.

I found lots of examples of doing similar things with other languages, but the purpose of this is not to only solve the problem, but also to learn Scala. Will someone please show me how to select that {....} part?

Upvotes: 5

Views: 4953

Answers (2)

Frank
Frank

Reputation: 10571

As Jens said, a regular expression usually suffices for this. However, the syntax is a bit different:

"""\{.*\}""".r

creates an object of scala.util.matching.Regex, which provides the typical query methods you may want to do on a regular expression.

In your case, you are simply interested in the first occurrence in a sequence, which is done via findFirstIn:

scala> """\{.*\}""".r.findFirstIn("""[{"insured_initials":"Tt","insured_surname":"Test"}=, _=1329793147757,callback=jQuery1707229194729661704_1329793018352""")
res1: Option[String] = Some({"insured_initials":"Tt","insured_surname":"Test"})

Note that it returns on Option type, which you can easily use in a match to find out if the regexp was found successfully or not.

Edit: A final point to watch out for is that the regular expressions normally do not match over linebreaks, so if your JSON is not fully contained in the first line, you may want to think about eliminating the linebreaks first.

Upvotes: 4

Jens Schauder
Jens Schauder

Reputation: 81862

Regexps should do the trick:

"\\{.*\\}".r.findFirstIn("your json string here")

Upvotes: 5

Related Questions