快速提取正則匹配我想從匹配regex模式的字符串中提取子字符串。所以我在找這樣的東西:func matchesForRegexInText(regex: String!, text: String!) -> [String] {
???}所以這就是我所擁有的:func matchesForRegexInText(regex: String!, text: String!) -> [String] {
var regex = NSRegularExpression(pattern: regex,
options: nil, error: nil)
var results = regex.matchesInString(text,
options: nil, range: NSMakeRange(0, countElements(text)))
as Array<NSTextCheckingResult>
/// ???
return ...}問題是,matchesInString給我一個數(shù)組NSTextCheckingResult,在哪里NSTextCheckingResult.range是類型的NSRange.NSRange是不相容的Range<String.Index>,所以它阻止了我使用text.substringWithRange(...)知道如何在沒有太多代碼行的情況下快速實現(xiàn)這個簡單的事情嗎?
3 回答

慕少森
TA貢獻2019條經(jīng)驗 獲得超9個贊
返回不僅匹配,而且 返回所有捕獲組
對于每一場比賽(見下面的例子) 而不是返回一個空數(shù)組,這個解決方案 支持可選匹配
避 do/catch
通過不打印到控制臺和 使用 guard
構(gòu)造 加 matchingStrings
作為 擴展到 String
SWIFT 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 2
extension 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)) : "" } } }}
- 3 回答
- 0 關(guān)注
- 712 瀏覽
添加回答
舉報
0/150
提交
取消