即使matchesInString() 方法将String 作为第一个参数,
它在内部与NSString 一起工作,并且必须给出范围参数
使用 NSString 长度而不是 Swift 字符串长度。否则会
对于“扩展字素簇”(例如“标志”)失败。
从 Swift 4 (Xcode 9) 开始,Swift 标准
库提供了在Range<String.Index> 之间转换的函数
和NSRange。
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
String(text[Range($0.range, in: text)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
例子:
let string = "??€4€9"
let matched = matches(for: "[0-9]", in: string)
print(matched)
// ["4", "9"]
注意: 强制解包 Range($0.range, in: text)! 是安全的,因为
NSRange 指的是给定字符串text 的子字符串。
但是,如果您想避免它,请使用
return results.flatMap {
Range($0.range, in: text).map { String(text[$0]) }
}
改为。
(Swift 3 及更早版本的旧答案:)
因此,您应该将给定的 Swift 字符串转换为 NSString,然后提取
范围。结果将自动转换为 Swift 字符串数组。
(Swift 1.2 的代码可以在编辑历史中找到。)
Swift 2 (Xcode 7.3.1):
func matchesForRegexInText(regex: String, text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substringWithRange($0.range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
例子:
let string = "??€4€9"
let matches = matchesForRegexInText("[0-9]", text: string)
print(matches)
// ["4", "9"]
Swift 3 (Xcode 8)
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = text as NSString
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range)}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
例子:
let string = "??€4€9"
let matched = matches(for: "[0-9]", in: string)
print(matched)
// ["4", "9"]