慕少森
我的答案建立在给定的答案之上,但通过添加额外的支持,使正则表达式匹配更加健壮:返回不仅匹配,而且返回所有捕获组对于每一场比赛(见下面的例子)而不是返回一个空数组,这个解决方案支持可选匹配避do/catch通过不打印到控制台和使用guard构造加matchingStrings作为扩展到StringSWIFT 4.2//: Playground - noun: a place where people can playimport Foundationextension String {
func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.range(at: $0).location != NSNotFound
? nsString.substring(with: result.range(at: $0))
: ""
}
}
}}"prefix12 aaa3 prefix45".matchingStrings(regex: "fix([0-9])([0-9])")// Prints: [["fix12", "1", "2"], ["fix45", "4", "5"]]"prefix12"
.matchingStrings(regex: "(?:prefix)?([0-9]+)")// Prints: [["prefix12", "12"]]"12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["12", "12"]], other answers return an empty array here// Safely accessing the capture of the first match (if any):let
number = "prefix12suffix".matchingStrings(regex: "fix([0-9]+)su").first?[1]// Prints: Optional("12")SWIFT 3//: Playground - noun: a place where people can playimport Foundationextension String {
func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.rangeAt($0).location != NSNotFound
? nsString.substring(with: result.rangeAt($0))
: ""
}
}
}}"prefix12 aaa3 prefix45".matchingStrings(regex: "fix([0-9])([0-9])")// Prints: [["fix12", "1", "2"], ["fix45", "4", "5"]]"prefix12".
matchingStrings(regex: "(?:prefix)?([0-9]+)")// Prints: [["prefix12", "12"]]"12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["12", "12"]], other answers return an empty array here// Safely accessing the capture of the first match (if any):let
number = "prefix12suffix".matchingStrings(regex: "fix([0-9]+)su").first?[1]// Prints: Optional("12")SWIFT 2extension String {
func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matchesInString(self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.rangeAtIndex($0).location != NSNotFound
? nsString.substringWithRange(result.rangeAtIndex($0))
: ""
}
}
}}