import Foundation
let pattern = #"(?:^| )(\w+) : ?(?!\w+ : )(?:(.*?)(?= \w+ :|$))?"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"bypass_first_page : x_company : x_cust_id : 12345 x_customer_ip : x_customer_tax_id : x_description : 98765 x_duty : x_email_customer : an_example@example.com x_fax : x_footer_email_receipt : x_fp_hash : 747ffeddfe4e106a9c67363ebff996ad x_fp_timestamp : 1525100766 x_invoice_num : R000098765 x_login : MY-LOGIN-ID x_logo_url : x_merchant_email : x_method : x_phone : (416) 555-1212 x_po_num : x_receipt_link_method : GET x_reference_3 : 1234 x_relay_response : TRUE x_relay_url :"#
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