我正在尝试解析此字符串:
"@hello this is a string @really :dialogue I certainly agree #definitely #concur -goodbye"
进入这个:
at-sign: "@hello" // only the first encounter
content: "this is a string @really" // further @'s are all in content
notes: ["dialogue" : "I certainly agree"]
hashtags: ["#definitely", "#concur"]
keywords: ["-goodbye"] // could be multiple
我将字符串分隔成一个数组并在数组上迭代并手动挑选出部分字符串。
static func processText(text: String) {
var stext = text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
var components: [String] = stext.componentsSeparatedByString(" ")
var atsign: String?
var contentList = [String]()
var tags = Set<String>()
var notes = [String: String]()
var encounterNotes: Bool = false
var notesKey = ""
var keyword: String?
for (idx, value) in enumerate(components) {
if hasPrefixAtSign(value) && atsign == nil {
encounterNotes = false
atsign = value
} else if hasPrefixHashTag(value) {
encounterNotes = false
tags.insert(value)
} else if hasPrefixKeyword(value) && keyword == nil {
encounterNotes = false
keyword = value
} else if hasPrefixNotes(value) {
attribute = dropFirst(value.lowercaseString)
encounterNotes = true
} else if encounterNotes == true {
if var aval = notes[attribute] {
aval = aval + " " + value
notes[attribute] = aval
} else {
notes[attribute] = value
}
} else {
encounterNotes = false
contentList += [value]
}
}
var content = " ".join(contentList)
}
这是我到目前为止所拥有的。 它有效但有没有更好(更快)的方法来解析它使用NSRegularExpression或NSScanner?