import Foundation
let pattern = #"(?<!(i|e))[.,!?][a-zA-Z0-9]"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
The problem:
Match lack of space following a fullstop/period. BUT! don't match on "i.e." and "e.g."
The current attempt above is not robust, only matches the "i" of "i.e." and "e" of "e.g." and, worse, allows all other sentences ending with "i" or "e".
Example source:
PASS: This is a test (i.e. something).Match M with no space. Don't match i.e.
PASS: This is a test (e.g. Something).Match M with no space. Don't match e.g.
PASS: This is a test (q.v. something).Match M with no space. DO match .v (not required)
PASS: This is a test.match the m.
PASS: Is this a test?Match the M.
PASS: This is a test!Match the M.
These all fail:
(?<!(i\.e|e\.g))[.,!?][a-zA-Z0-9]
(?<!(i\.e\.|e\.g\.))[.,!?][a-zA-Z0-9]
(?<!(i\.e|e\.g))(\.|\!|\?)\s+“?[a-z]
Current working copy:
(?<!(i|e))[.,!?][a-zA-Z0-9]
"""#
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