import Foundation
let pattern = #"""
(?(DEFINE)
(?<tagnames> @CUSTOM-AT-1 | @CUSTOM-AT-2)
(?<number> -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )
(?<boolean> true | false | null )
(?<string> \" ([^\"\\\\]* | \\\\ [\"\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* \" )
(?<array> \[ (?: (?&json) (?: , (?&json) )* )? \s* \] )
(?<pair> \s* (?&string) \s* : (?&json) )
(?<object> \{ (?: (?&pair) (?: , (?&pair) )* )? \s* \} )
(?<fieldname> [a-zA-Z0-9\_\-]+ )
(?<json> \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) )
(?<fieldlist> (?: (?&fieldname) (?: , (?&fieldname) )+ )+ ) )
(?<actiontag> (?&tagnames)
)
(?:\=
(?'params'
(?:
(?'match_list'(?&fieldlist))
|
(?'match_json'(?&json))
|
(?'match_string'(?:[[:alnum:]\_\-]+))
)
)
)
"""#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive, .allowCommentsAndWhitespace])
let testString = #"""
@FIELDLIST=field_1,field_2
@STRING="Bar"
@JSON={"foo":"bar"}
@CUSTOM-AT-2={"strict":true, "targets":["field_3", "field_7"], "title":"Custom Title", "message":"This is a custom message"}
@CUSTOM-AT-1={"strict":true, "targets":["field_3", "field_7"], "title":"Custom Title", "message":"This is a custom message"}
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression