import Foundation
let pattern = #""title":\s*"([^"]+)""#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = ##"""
{
"kind": "books#volumes",
"totalItems": 1,
"items": [
{
"kind": "books#volume",
"id": "HDvHjwEACAAJ",
"etag": "+2K7d2N2VNg",
"selfLink": "https://www.googleapis.com/books/v1/volumes/HDvHjwEACAAJ",
"volumeInfo": {
"title": "Fahrenheit 451",
"authors": [
"Ray Bradbury"
],
"publisher": "Voyager",
"publishedDate": "2013",
"description": "The terrifyingly prophetic novel of a post-literate future Guy Montag is a fireman. His job is to destroy the most illegal of commodities, the source of all discord and unhappiness, the printed book.",
<div style="padding-left:2em;">
• Location:
Northern Virginia, ☎ 202-210-5936
</div>
<div style="padding-left:2em;"><br />• Post ID: 1234567 washingtondc</div>
<div id="OtherAdsByThisUser" data-oid="7654321">
"""##
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