import Foundation
let pattern = #"(?=.*(?:epub|digital|e-?(?:ISBN|book))).*ISBN(?: *13)?:?\s+\K(\d(?:-?\d){12})"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = #"""
These should match to indicate they are eBook ISBNs:
ISBN 978-1-9821-8584-8 (ebook)
EISBN: 9781101487280
eISBN: 978-1-4406-3132-0
eISBN 9781429902304
Ebook ISBN: 9780593547342
eBook ISBN: 9780804139038
e-ISBN 978-0-765-37686-2
Digital Edition MAY 2017 ISBN: 978-0-06-244198-0
ISBN 13: 978-0-9999999-9-9 (eBook edition)
EPub © Edition JUNE 2003 ISBN: 9780061739200
But then these should not match, as they are assumbed to be print copy ISBNs:
Print ISBN: 978-0-06-244197-3
ISBN 978-1-9821-8582-4
ISBN 9780804139021
ISBN-13: 978-1-4299-6030-4
ISBN 13: 978-0-9999999-9-9 (Paperback edition)
"""#
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