How to use regular expression in Swift

Issue #551

Find matches

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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

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

Common expression

Version

1
2
3
#"\((\d+\.)?(\d+\.)?(\*|\d+)\)"#

(11.0.1)

Read more

Comments