import Foundation
let pattern = #"r"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
Ex1. This is a random sentence.1,7,9 This is a sentence followed by it.
Output = This is a random sentence. 1,7,9 This is a sentence followed by it.`#space after the period will do.
Ex2. I love football.1,7,24`I also like cricket.
Output = I love football. 1,7,24`I also like cricket.
Ex3. ESD for undifferentiated cancers.[1][7]Cancers can be treata
ble.
Output = ESD for undifferentiated cancers. [1][7]Cancers can be treatable. #space after the period
EX4. |Age, n (%) | | |< | |
| | | |0.001 | |
| |> 65 years |641 (44.3) |28 (24.8) | |669 (42.9)|
| |? 65 years |806 (55.7) |85 (75.2) | |891 (57.1)|
# Tables should be untouched
EX5.75.6% vs. 54.0% # untouched
EX6. ask@to.in # should be untouched
EX7. Decimal numbers 22.3456 # should be untouched
EX8.
"""##
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