在Scala中选择两个字符之间的子字符串 [英] Select substring between two characters in Scala

查看:61
本文介绍了在Scala中选择两个字符之间的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 HTTP 请求中得到一个乱码的 JSON 字符串,所以我正在寻找一个临时解决方案来仅选择 JSON 字符串.

request.params() 返回这个:

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

我想要从{"开头到}"结尾的所有内容.

我发现了很多用其他语言做类似事情的例子,但这样做的目的不仅仅是解决问题,也是为了学习Scala.有人会告诉我如何选择那个 {....} 部分吗?

解决方案

正如 Jens 所说,正则表达式通常就足够了.但是,语法有点不同:

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

创建一个 scala.util.matching 的对象.正则表达式,它提供了您可能希望对正则表达式执行的典型查询方法.

在您的情况下,您只对序列中的第一次出现感兴趣,这是通过 findFirstIn 完成的:

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

请注意,它返回 Option 类型,您可以轻松地在匹配中使用它来确定是否成功找到了正则表达式.

最后一点需要注意的是,正则表达式通常不匹配换行符,因此如果您的 JSON 未完全包含在第一行中,您可能需要考虑先消除换行符.

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?

解决方案

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.

这篇关于在Scala中选择两个字符之间的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆