import Foundation
let pattern = #"[A-Z]\S*\.[^\S\r\n]+[A-Z]|(?:^|[.!?][\t ]+)([A-Z]\S*)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
We went to Dr. Smith's office
This is a proper sentence. It is followed by another sentence. What happens when an abbreviation like NASA enters the scene? What about N.A.S.A with the dots in between?
It is NASA! No one will convince me otherwise!
N.A.S.A. at the start of a sentence? N.A.S.A. immediately after?
At the end of the sentence: NASA. But also with the dots: N.A.S.A. Filler sentence here.
The compromise of catching situations like Dr. Smith is that words at the end of a sentence cannot start with a capital letter.
While This Regex Doesn't Match Every Word As The Start Of A Sentence Here, It Won't Detect The Start Of The Next Sentence. Case in point.
Abbreviations like LIKE currently pose a problem.
The second regex has false negatives: it will fail to match `So` in `This is sentence is English. So is this one.`
"""#
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