import Foundation
let pattern = ##"((\s*\b([a-zA-Z_]*)\b)\s*((\s*=\s*(('[\w\-_#@,.!@#$%^&*()\s]*')))|((\s+\bLIKE\b\s+('[\w\-_#@,.!@#$%^&*()\s]*')))|(((\s+\bIN\b\s+\('[\w\-_#@,.!@#$%^&*()\s]+'(, '[\w\-_#@,.!@#$%^&*()\s]+')*\)))))((\s*\b(AND|OR)\b\s*)(\s*\b([a-zA-Z_]*)\b)\s*((\s*=\s*(('[\w\-_#@,.!@#$%^&*()\s]*')))|((\s+\bLIKE\b\s+('[\w\-_#@,.!@#$%^&*()\s]*')))|(((\s+\bIN\b\s+\('[\w\-_#@,.!@#$%^&*()\s]+'(, '[\w\-_#@,.!@#$%^&*()\s]+')*\))))))*)"##
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
sponsor_type_trial_company = 'Sponsor' AND
brief_title_trial LIKE '%heme%' AND brief_title_trial LIKE '%basket%'
outcome_trial_primary_outcome = 'Bladder Cancer'
AND sponsor_type_trial_company = 'Sponsor' AND
overall_status_trial IN ('Recruiting', 'Enrolling by invitation') AND trial_status_trial = 'Open' AND official_title_trial LIKE '%Japan%'
overall_status_trial IN ('Recruiting', 'Not yet recruiting', 'Active, not recruiting') AND biomarker_strategy_trial_biomarker = 'HER2 low' AND indication_trial_indication = 'Breast Cancer'
trial_phase_trial='Phase 3' AND stage_trial_indication_stage='Stage IV' AND outcome_acronym_trial_primary_outcome='PFS'
"""#
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