[英]Trim double quotation mark(") from a string
I have a string and I need to delete following characters 我有一个字符串,我需要删除以下字符
\\ " { ] } \\“{]}
from a string. 从一个字符串。 Everything working fine except the double quotation mark. 除了双引号外,一切正常。
My string is : 我的字符串是:
{"fileId":1902,"x":38,"y":97} { “FILEID”:1902, “×”:38, “Y”:97}
after the following operations are performed: 执行以下操作后:
let charsToBeDeleted = CharacterSet(charactersIn: "\"{]}")
let trimmedStr = str.trimmingCharacters(in: charsToBeDeleted)
print(trimmedStr)
prints: 打印:
fileId":1902,"x":38,"y":97 FILEID “:1902,” × “:38,” Y“:97
It trimmed first double quotation mark but not the other ones. 它修剪了第一个双引号而不是其他引号。 How can I trim this string without double quotation marks? 如何在没有双引号的情况下修剪此字符串?
trimmingCharacters(in
is the wrong API. It removes characters from the beginning ( {"
) and end ( }
) of a string but not from within. trimmingCharacters(in
是错误的API。它从字符串的开头( {"
)和end( }
)中删除字符,但不从内部删除。
What you can do is using replacingOccurrences(of
with Regular Expression option. 你可以做的是使用replacingOccurrences(of
使用正则表达式选项)。
let trimmedStr = str.replacingOccurrences(of: "[\"{\\]}]", with: "", options: .regularExpression)
[]
is the regex equivalent of CharacterSet
. []
是CharacterSet
的正则表达式。
The backslashes are necessary to escape the double quote and treat the closing bracket as literal. 反斜杠是逃避双引号并将结束括号视为文字所必需的。
But don't trim . 但不要修剪 。 This is a JSON string. 这是一个JSON字符串。 Deserialize it to a dictionary 将其反序列化为字典
let str = """
{"fileId":1902,"x":38,"y":97}
"""
do {
let dictionary = try JSONSerialization.jsonObject(with: Data(str.utf8)) as! [String:Int]
print(dictionary)
} catch {
print(error)
}
Or even to a struct 甚至是结构
struct File : Decodable {
let fileId, x, y : Int
}
do {
let result = try JSONDecoder().decode(File.self, from: Data(str.utf8))
print(result)
} catch {
print(error)
}
I haven't test this but it would be something like this: 我没有测试过,但它会是这样的:
You may have to check if the escape of characters for \\
and "
inside the set is used correctly. 您可能必须检查是否正确使用了\\
和"
集合内部的字符转义。
let charsToDelete:Set<Character> = ["\\", "\"", "{", "]", "}"]
str.removeAll(where: { charsToDelete.contains($0)})
print(str)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.