寻找一种使用Swift获取组名的方法,我在C#(How do I get the name of captured groups in a C# Regex?)中使用GetGroupNames找到了信息,但找不到类似的东西。希望能够说出一个小组的存在。
目前使用下面的代码...
let search = "Agora.2010.1080p.BluRay.x264.mp4"
let regex "^(Agora.)(?<"group name">2010)?"
let return_results = regex(for: regex, in: search)
func regex(for expression: String, in string: String) -> [String]? {
guard let regex = try? NSRegularExpression(pattern: expression, options: [.caseInsensitive]) else { return nil }
let results = regex.matches(in: string, range: NSRange(string.startIndex..., in: string))
guard !results.isEmpty else { return nil }
var values: [String] = []
guard regex.numberOfCaptureGroups > 0 else { return nil }
for r in 1...(regex.numberOfCaptureGroups) {
let range = results[0].range(at: r)
if range.length > 0 {
let start = string.index(string.startIndex, offsetBy: range.location)
let end = string.index(start, offsetBy: range.length)
let value = string[start..<end]
if !value.isEmpty {
let value_string = String(value)
values.append(value_string)
}
}
}
return values
此刻,它仅查找任何组。我要返回的是[[group name]:“ value”]的字典列表。我尝试从附加链接...“ regex.Match(line).Groups”和“ regex.GetGroupNames()”尝试不存在。