import Foundation
let pattern = #"((?<=\|\s)([^|]+)(?!\|\s))"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
- [x] Example of a completed task.
- [x] ! Example of a completed task.
- [x] ? Example of a completed task.
| | Task name | Plan | Actual | File |
| :---- | :-------------------------------------- | :---------: | :---------: | :------------: |
| [x] | Task one with a reasonably long name. | 08:00-08:45 | 08:00-09:00 | [[task-one]] |
| [x] ! | Task two with a reasonably long name. | 09:00-09:30 | | [[task-two]] |
| [x] ? | Task three with a reasonably long name. | 11:00-13:00 | | [[task-three]] |
Description:
$1: the left [ and the right ] brackets when the symbol x is in-between
$2: the symbol x in between the brackets [ and ]
$3: the modifier ! that follows after [x]
$4: the modifier ? that follows after [x]
$5: the text that follows [x] without a modifier, e.g., [x] This is targeted.
$6: the text that follows [x] !
$7: the text that follows [x] ?
Groups $5 to $7 should exclude the any | symbols in their captures.
"""#
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