Swift 5.2正则表达式如何实现非贪婪搜索效果
Swift 5.2 正则非贪婪匹配替代方案
在Swift 5.2中使用NSRegularExpression时,U(全局非贪婪反转)标记不受支持。此前测试中,该标记可让正则默认非贪婪,从而正确匹配两段独立的- examples:内容块;去掉U标记后,正则会贪婪匹配成一个完整大区块,无法拆分出目标内容。
需通过显式非贪婪量词(如.*?)替代U标记的效果,同时调整正则选项以支持跨多行匹配,最终获取两段独立的匹配结果。
修改后的完整代码
import Foundation // 使用.*?实现非贪婪匹配,替代U标记 let pattern = #"- examples: \[\{.*?\}\}\]"# // 启用dotMatchesLineSeparators让.匹配换行,anchorsMatchLines适配行首尾锚点 let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .dotMatchesLineSeparators]) let testString = #"""" /** Gets a list of custom fields. - GET - OAuth: - name: - examples: [{contentType=application/json, example={ "s" : [ { "name" : "name", }, { "name" : "name", } ], "fields" : [ { "items" : [ "listItems", "listItems" ], "name" : "name", "message" : "message" }, }, { "items" : [ "listItems", "listItems" ], "name" : "name", } ] }}] - returns: Request<Fields> */ /** Gets a - examples: [{contentType=application/json, example={ "fields" : [ { "name" : "name", } ], "fields" : [ { "listItems" : [ "listItems", "listItems" ], "name" : "name", } ] }}] - returns: Request<fields> */ """# let stringRange = NSRange(location: 0, length: testString.utf16.count) let matches = regex.matches(in: testString, range: stringRange) var result: [String] = [] for match in matches { let nsRange = match.range(at: 0) guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue } let string = (testString as NSString).substring(with: nsRange) result.append(string) } // 输出两段匹配结果 result.forEach { print($0 + "\n---") }
关键说明
- 替换U标记:用
.*?(非贪婪匹配任意字符)替代U标记的全局非贪婪效果,确保正则匹配到最近的}}]就停止,而非匹配到最后一个。 - 正则选项调整:添加
.dotMatchesLineSeparators,让.可以匹配换行符,否则无法跨多行捕获examples块内的完整内容。 - 简化匹配逻辑:直接匹配完整的
- examples: [{...}}]结构,无需多余分组,提升代码可读性。
预期输出
- examples: [{contentType=application/json, example={ "s" : [ { "name" : "name", }, { "name" : "name", } ], "fields" : [ { "items" : [ "listItems", "listItems" ], "name" : "name", "message" : "message" }, }, { "items" : [ "listItems", "listItems" ], "name" : "name", } ] }}] --- - examples: [{contentType=application/json, example={ "fields" : [ { "name" : "name", } ], "fields" : [ { "listItems" : [ "listItems", "listItems" ], "name" : "name", } ] }}] ---
内容的提问来源于stack exchange,提问作者ashokds
相关产品推荐
相关产品推荐

