如果你真的想在最后一个逗号后面的字符,你可以使用正则表达式:
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