问题描述
我正在尝试快速编写JSON解析器.我正在编写用于解析JSON代码不同部分的函数.我编写了一个字符串解析器,该字符串解析器通过检查\开头来检测JSON数据中的一个字符串,如果我遇到另一个\",则将其分离并作为字符串返回,但是当我遇到以下JSON文本时:
I am trying to write a JSON parser in swift. I am writing functions for parsing different parts of JSON code. I wrote a string parser which detects a string from the JSON data, by checking the start with \" and if I meet with another \" it is separated and returned as a String but when I met with this JSON text:
{"gd$etag": "W\/\"D0QCQX4zfCp7I2A9XRZQFkw.\""}
在上面的情况下,我编写的函数失败了,因为在值部分中,它必须将整体识别为String,而我的函数仅是收集
the function I wrote failed in the above case since in the value part it has to recognise the whole as String while mine is working to collect only
W\/
因为我给出了以\开头和结尾的条件,当我在线搜索时,我了解到这与正则表达式有关.所以帮我解决这个问题!
Since I gave the condition as starting and ending with \"when I searched online I understood it is something in relation to regular expressions. So help me out to solve this!
推荐答案
if first(jsonString) == "\"" {
jsonString.removeAtIndex(jsonString.startIndex)
for elem in jsonString {
if elem == "\\" {
s = 1
parsedString.append(elem)
jsonString.removeAtIndex(jsonString.startIndex)
continue
}
if s == 1 && elem == "\""{
parsedString.append(elem)
jsonString.removeAtIndex(jsonString.startIndex)
s = 0
continue
}
else if elem == "\""{
jsonString.removeAtIndex(jsonString.startIndex)
break
}
parsedString.append(elem)
jsonString.removeAtIndex(jsonString.startIndex)
s = 0
}
此代码可让我解决我的问题,以使其保持快速状态.
This code lets me solve my issue to keep it pure swift.
这篇关于如何快速使用正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!