This is my response
scala > val a= """{"string":"{\"data\":{\"id\":\"2c91809f4ef7678b014ef86ee28511c2\",\"unitName\":\"gatlir1\",\"owner\":\"gatlir1\",\"description\":\"gatlir1\",\"nofChairs\":0,\"nofBeds\":0,\"nofApptStartWithInHour\":0,\"nofApptDischargeWithInHour\":0,\"modifiedDateTime\":\"Aug 4, 2015 4:18:13 AM\"},\"status\":\"SUCCESS\",\"message\":\"unit_save\"}"}"""
i need to fetch id value from that response in scala. i have stored response in one variable. and i have written regular expression for that and stored in another variable.
Here is the problem , i am getting error. RegEx:
scala> val b= """{\"id\":\"(\w+)\""""
while inserting regex into "b" , i didn't get any error, but while comparing i am getting error
if i write expression like this
scala> a.matches(b)
error:
java.util.regex.PatternSyntaxException: Illegal repetition
{\"id\":\"(\w+)\"
at java.util.regex.Pattern.error(Pattern.java:1955)
at java.util.regex.Pattern.closure(Pattern.java:3157)
at java.util.regex.Pattern.sequence(Pattern.java:2134)
at java.util.regex.Pattern.expr(Pattern.java:1996)
at java.util.regex.Pattern.compile(Pattern.java:1696)
at java.util.regex.Pattern.<init>(Pattern.java:1351)
at java.util.regex.Pattern.compile(Pattern.java:1028)
at java.util.regex.Pattern.matches(Pattern.java:1133)
at java.lang.String.matches(String.java:2109)
could any one help me in this..
Why are you using regular expressions here? Just read the JSON. JSON is not a regular language, and can not be easily described with regex.
Here's one of many library's that will parse JSON for Scala https://github.com/json4s/json4s
It'll also make accessing any of the other objects inside much easier.
您应该转义{
:
val b= """\{\"id\":\"(\w+)\""""
Here is the fixed code:
val a= """{"string":"{"data":{"id":"2c91809f4ef7678b014ef86ee28511c2","unitName":"gatlir1","owner":"gatlir1","description":"gatlir1","nofChairs":0,"nofBeds":0,"nofApptStartWithInHour":0,"nofApptDischargeWithInHour":0,"modifiedDateTime":"Aug 4, 2015 4:18:13 AM"},"status":"SUCCESS","message":"unit_save"}"}"""
val b= """\{"id":"(\w+)""".r
val allMatches = b.findAllMatchIn(a)
allMatches.foreach { m =>
println(m.group(1))
}
It prints: 2c91809f4ef7678b014ef86ee28511c2
.
See demo
Note you do not have to escape double quotes inside """
quoted strings (see this SO answer ).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.