Issue #551

Find matches

import Foundation

public extension String {
    func matches(pattern: String) throws -> [String] {
        let regex = try NSRegularExpression(pattern: pattern)
        let results = regex.matches(in: self, options: [], range: NSRange(self.startIndex..., in: self))
        return results.compactMap({ result in
            if let range = Range(result.range, in: self) {
                return String(self[range])
            } else {
                return nil
            }
        })
    }

    func hasPattern(pattern: String) throws -> Bool {
        return try !matches(pattern: pattern).isEmpty
    }
}

func testRegex() throws {
    let string = "iPad Air (11.0.1) [7A5EAD29-D870-49FB-9A9B-C81079620AC9] (Simulator)"
    let matches = try string.matches(pattern: #"\[.+\]"#)
    XCTAssertEqual(matches.first, "[7A5EAD29-D870-49FB-9A9B-C81079620AC9]")
}

Range and NSRange

let string: String
let nsRange: NSRange = NSRange(string.startIndex..., in: string)
let string: String
let nsRange: NSRange
let range: Range = Range(nsRange, in: string)
let substring: Substring = string[range]

Common expression

Version

#"\((\d+\.)?(\d+\.)?(\*|\d+)\)"#

(11.0.1)

Read more