如果你真的想在最後一個逗號後面的字符,你可以使用正則表達式:
let string = "Hamilton, A"
let regex = try! NSRegularExpression(pattern: ",\\s*(\\S[^,]*)$")
if let match = regex.firstMatch(in: string, range: string.nsRange), let result = string[match.range(at: 1)] {
// use `result` here
}
凡在雨燕4:
extension String {
/// An `NSRange` that represents the full range of the string.
var nsRange: NSRange {
return NSRange(startIndex ..< endIndex, in: self)
}
/// Substring from `NSRange`
///
/// - Parameter nsRange: `NSRange` within `utf16`.
/// - Returns: Substring with the given `NSRange`, or `nil` if the range can't be converted.
subscript(nsRange: NSRange) -> Substring? {
guard let range = Range(nsRange, in: self) else { return nil }
return self[range]
}
}
來源
2016-04-28 05:02:54
Rob
是否正則表達式的解決方案也行,如果有名單上有兩個以上的名字? – user3798602
對不起,我只是問,因爲它說firstMatchInString不是最後一個。謝謝 – user3798602
好的,我明白了這個混亂。但是,如果你看看我的正則表達式字符串,最後一個字符是'$',它表示「匹配字符串的末尾」。因此,你只會得到一個匹配,最後一個匹配(如果有的話)。我只使用'firstMatchInString',因爲由於我們只獲得最後一個,所以不需要枚舉,只需要在字符串末尾抓住「first」匹配。 – Rob