我有一个看起来像的字符串:
"OS-MF sessionId='big_super-long-id_string', factor='PASSCODE'"
但我需要获取该字符串中的sessionId。有人可以迅速帮助我吗?我已经尝试过正则表达式,但无法让它发挥作用。
答案 0 :(得分:3)
如果您想使用正则表达式,您可以使用以下功能匹配模式的任何出现:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
let regex = NSRegularExpression(pattern: regex, options: nil, error: nil)!
let nsString = text as NSString
let results = regex.matchesInString(text,
options: nil, range: NSMakeRange(0, nsString.length))
as! [NSTextCheckingResult]
return map(results) { nsString.substringWithRange($0.range)}
}
您可以使用以下正则表达式对其进行测试:
let myStringToBeMatched = "OS-MF sessionId='big_super-long-id_string', factor='PASSCODE'"
var results = self.matchesForRegexInText("(?<=sessionId=')(.*)(?=',)", text: myStringToBeMatched)
for item in results {
println(item)
}
输出应为:
big_super-long-id_string
注意:
(?<=sessionId=') means preceded by sessionId='
(.*) means any character zero or more times
(?=',) means followed by ',
您可以阅读有关正则表达式here
的更多信息我希望这对你有所帮助。
答案 1 :(得分:1)
let input = "OS-MF sessionId='big_super-long-id_string', factor='PASSCODE'"
let sessionID = input.componentsSeparatedByString("sessionId='").last!.componentsSeparatedByString("',").first!
println(sessionID) // "big_super-long-id_string"