import Foundation
let pattern = ##"^(?:\((?P<imp>[A-Z])\)\ )?(?P<dued>(?:2[0-1][0-9]{2}\-(?:0[0-9]|1[0-2])\-(?:[0-2][0-9]|3[0-1]))|\?)\ (?:\+(?P<proname>[a-zA-Z0-9]+)(?:\#(?P<pronum>[0-9]+))?\ )?(?:\$(?P<startd>2[0-1][0-9]{2}\-(?:0[0-9]|1[0-2])\-(?:[0-2][0-9]|3[0-1]))(?:\^(?P<repeat>\d*(?:D|W|M|Y)(?:\,\d*(?:D|W|M|Y)+)*))?\ )?(?P<todo>.+?(?=(?:\ (?:\@|\&))|$))(?P<contexts>(?:\ \@\S+)*)(?P<tags>(?:\ \&\S+)*)"##
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
(A) 2016-10-23 +projectB $2016-10-03 to be completed as soon as possible @context_bar
(A) 2016-11-01 +projectA $2016-09-25 job to complete @context @context_two
(B) ? +houseworks $2016-10-04^2D,W lavoro importante &TAG_FOO &TAG_BAR
2016-12-15 +projectA#2 $2016-09-25 second job related to the same project @another_context
? +houseworks $2016-10-02^3D altro lavoro di casa @context_bar &TAG
? +projectA#3 $2016-09-25 third job of the same project @foo_context &WAIT
? +projectA#4 $2016-09-25 fourth job, needs third to be completed first
2016-11-23 $2015-06-23^4Y another job without project @context_foo @context_bar &TAG_A &TAG_B
? minimal job like email fra@me.com
"""##
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