2016-04-28 111 views
-1

我有一个Scala的字符串是这样的:正则表达式Scala的字符串

的HttpResponse({ “数据”:[{ “文”: “我爱泰坦尼克号”, “极”:4, “元” :{“language”:“en”}}]} ,200,Map(Content-Length→Vector(76),Content-Type→Vector(application/json; charset = ISO-8859-1) - > Vector(Thu,28 Apr 2016 16:51:45 GMT),Server - > Vector(Google Frontend),Status - > Vector(HTTP/1.1 200 OK)))

我想提取在极性字4之后的整数是在scala中使用正则表达式。

+0

难道你不能以HttpResponse或json的形式获取该信息,而不是那个**丑陋的**字符串吗? – pedrorijo91

回答

0
scala> val str = """HttpResponse({"data":[{"text":"I love Titanic.","polarity":4,"meta":{"language":"en"}}]} ,200,Map(Content-Length -> Vector(76), Content-Type -> Vector(application/json; charset=ISO-8859-1), Date -> Vector(Thu, 28 Apr 2016 16:51:45 GMT), Server -> Vector(Google Frontend), Status -> Vector(HTTP/1.1 200 OK)))""" 
str: String = HttpResponse({"data":[{"text":"I love Titanic.","polarity":4,"meta":{"language":"en"}}]} ,200,Map(Content-Length -> Vector(76), Content-Type -> Vector(application/json; charset=ISO-8859-1), Date -> Vector(Thu, 28 Apr 2016 16:51:45 GMT), Server -> Vector(Google Frontend), Status -> Vector(HTTP/1.1 200 OK))) 

scala> """polarity":(\d+),""".r.findFirstMatchIn(str).map(_.group(1)) 
res15: Option[String] = Some(4) 

但是你可能更想要把json解析成case类。