Looking for a way to get Group Names using Swift, I found info using GetGroupNames in C# (How do I get the name of captured groups in a C# Regex?) but can't find anything similar. Want to be able to tell is a group exists.
At the moment using code below ...
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
At the moment this just looks for any groups. What I want is to return is a Dictionary list of ["group name":"value"]. I've tried from attached link ... "regex.Match(line).Groups" & "regex.GetGroupNames()" which do not exist.