import Foundation
let pattern = ##"""
# Chunk or note time.
(?<= \| )
(?: \s+) (\() ([0-2][0-9]) (:) ([0-5][0-9]) (\))
(?= \s+ \|)
|
# Revision title.
(?<= \s \| \s)
(\(.+\s\#\d+\))
(?= \s+ \|)
|
# Chunk title.
(?<= \| \s [0-2][0-9] : [0-5][0-9] - [0-2][0-9] : [0-5][0-9] \s \| \s )
(?! \[ | \s* \| )
(?:\s*)? (.+?)
(?= \s+ \|)
|
# Chunk note.
(?<= \s \| \s ) (?! -{2} )
(- .+?)
(?= \s+ \|)
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .allowCommentsAndWhitespace])
let testString = ###"""
[^\S\n] (?:\s*\r\n|\s*\r|\s*\n)
# Time block
| Time | Block |
| ----------: | :---------------- |
| (00:00) | (Revision #1) |
| | |
| 00:00-00:00 | Chunk |
| | - Note w/ details |
| 00:00-00:00 | Some meeting |
| 11:00-13:00 | Chunk |
| 13:00 | - Note w/ details |
| | |
| (00:00) | (Revision #1) |
| 00:00-00:00 | Chunk |
| | - Note w/ details |
## Time Tracking
| Tracker | Task | Backlog |
| ----------: | :---------------------------------- | :------------ |
| 08:04-08:53 | [x] * Task for deep work block (#1) | [[wiki.link]] |
| 09:07-09:56 | | Don't match |
| 98m | | |
| | | |
| 00:00-00:00 | Can Match | |
| | Don't Match | |
| 00:00-00:00 | | Don't match |
Group 1: `(` for time
Group 2: `00` hour (for chunk)
Group 3: `:` (for chunk)
Group 4: `00` minute (for chunk)
Group 5: `)` for time
Group 6: `(Revision #1)`
Group 7: `Chunk`or `Some meeting`
Group 8: `- Note w/ details`
"""###
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