快速提取正则匹配我想从匹配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给我一个数组NSTextCheckingResult,在哪里NSTextCheckingResult.range是类型的NSRange.NSRange是不相容的Range<String.Index>,所以它阻止了我使用text.substringWithRange(...)知道如何在没有太多代码行的情况下快速实现这个简单的事情吗?
3 回答
慕少森
TA贡献2019条经验 获得超9个赞
返回不仅匹配,而且 返回所有捕获组
对于每一场比赛(见下面的例子) 而不是返回一个空数组,这个解决方案 支持可选匹配
避 do/catch
通过不打印到控制台和 使用 guard
构造 加 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 关注
- 684 浏览
添加回答
举报
0/150
提交
取消