gpt4 book ai didi

swift - 如何一次运行多个 NSRegularExpression

转载 作者:搜寻专家 更新时间:2023-11-01 05:32:38 26 4
gpt4 key购买 nike

我有一堆NSRegularExpression,我想运行一次。任何人都知道该怎么做?

目前我在 .forEach 中执行此操作,出于性能原因,我认为这不是最好的主意

每个 NSRegularExpression 需要匹配不同的模式,匹配后我需要处理每种不同的匹配。例如,如果我与数组中的第一个正则表达式匹配,我需要做一些与第二个不同的东西……

let test: String = "Stuff"
let range: NSRange = // a range

var regexes = [NSRegularExpression] = // all of my regexes
regexes.forEach { $0.matches(in: text, options: [], range: range) }

谢谢你的帮助

最佳答案

如果您使用捕获组和 OR 表达式将多个正则表达式连接起来,您可以将它们作为一个进行评估。

如果你想搜索:languageObjective-CSwift 字符串你应该使用这样的模式: (语言)|(Objective-C)|(Swift)。每个捕获组都有一个顺序号,因此如果在源字符串中找到 language,则匹配对象会提供索引号。

您可以使用此 Playground 示例中的代码:

import Foundation

let sourceString: String = "Swift is a great language to program, but don't forget Objective-C."
let expresions = [ "language", // Expression 0
"Objective-C", // Expression 1
"Swift" // Expression 2
]
let pattern = expresions
.map { "(\($0))" }
.joined(separator: "|") // pattern is defined as : (language)|(Objective-C)|(Swift)

let regex = try? NSRegularExpression(pattern: pattern, options: [])
let matches = regex?.matches(in: sourceString, options: [],
range: NSRange(location: 0, length: sourceString.utf16.count))
let results = matches?.map({ (match) -> (Int, String) in // Array of type (Int: String) which
// represents index of expression and
// string capture
let index = (1...match.numberOfRanges-1) // Go through all ranges to test which one was used
.map{ Range(match.range(at: $0), in: sourceString) != nil ? $0 : nil }
.compactMap { $0 }.first! // Previous map return array with nils and just one Int
// with the correct position, lets apply compactMap to
// get just this number

let foundString = String(sourceString[Range(match.range(at: 0), in: sourceString)!])
let position = match.range(at: 0).location
let niceReponse = "\(foundString) [position: \(position)]"
return (index - 1, niceReponse) // Let's substract 1 to index in order to match zero based array index
})

print("Matches: \(results?.count ?? 0)\n")
results?.forEach({ result in
print("Group \(result.0): \(result.1)")
})

如果你运行它,结果是:

How many matches: 3

Expression 2: Swift [position: 0]
Expression 0: language [position: 17]
Expression 1: Objective-C [position: 55]

希望我正确理解了您的问题,并且这段代码对您有所帮助。

关于swift - 如何一次运行多个 NSRegularExpression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53116274/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com