import Foundation
let pattern = #"(^([0-9[:punct:]0-9]+|\p{No}|\d\p{No}) ?\s* ?([0-9[:punct:]0-9]+|\p{No}|\d\p{No})* ?\w* (cup|tsp|tbps|tablespoon|teaspoon|small|medium|pint|ounce|pound))|(^(small|Large|medium|Fresh))"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = #"""
Should match:
1 Cups
2 tsp
3 tbps
1/2 tablespoon
3 tablespoons
1 tablespoon
3 teaspoons
1 small
Small chiles
23 Small chiles
1/2 a Small chile
1 1/2 cups kewpie
11/2 cups kewpie
1/3 cup fresh lemon juice
1 medium onion
Large
medium
Freshly
1½ cups Kewpie
½ cups Kewpie
1 pint
4 ounces
1 pound
2 pounds
Should not match:
1 Make the sauce
1 toast the bread
I want to make 1 piece of toast
"""#
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