-
Notifications
You must be signed in to change notification settings - Fork 3
/
String.swift
28 lines (24 loc) · 1.06 KB
/
String.swift
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
26
27
28
import Foundation
extension String {
// https://stackoverflow.com/q/27880650/3386893
func matchingStrings(regex: NSRegularExpression) -> [[String]] {
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSRange(self.startIndex..., in: self))
return results.map { result in
(0..<result.numberOfRanges).map { result.range(at: $0).location != NSNotFound
? nsString.substring(with: result.range(at: $0))
: ""
}
}
}
func matchingStringsWithRange(regex: NSRegularExpression) -> [[(string: String, range: NSRange)?]] {
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSRange(self.startIndex..., in: self))
return results.map { result in
(0..<result.numberOfRanges).map { result.range(at: $0).location != NSNotFound
? (string: nsString.substring(with: result.range(at: $0)), range: result.range(at: $0))
: nil
}
}
}
}