-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathString+RegEx.swift
More file actions
76 lines (62 loc) · 2.83 KB
/
Copy pathString+RegEx.swift
File metadata and controls
76 lines (62 loc) · 2.83 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import Foundation
// MARK: - String: RegularExpression Helpers
//
extension String {
/// Replaces all matches of a given RegEx using a provided block.
///
/// - Parameters:
/// - regex: the regex to use for pattern matching.
/// - options: the regex options.
/// - block: the block that will be used for the replacement logic.
///
/// - Returns: the new string.
///
public func replacingMatches(of regex: String, options: NSRegularExpression.Options = [], using block: (String, [String]) -> String) -> String {
let regex = try! NSRegularExpression(pattern: regex, options: options)
let fullRange = NSRange(location: 0, length: utf16.count)
let matches = regex.matches(in: self, options: [], range: fullRange)
var newString = self
for match in matches.reversed() {
let matchRange = range(fromUTF16NSRange: match.range)
let matchString = String(self[matchRange])
var submatchStrings = [String]()
for submatchIndex in 0 ..< match.numberOfRanges {
let submatchRange = self.range(fromUTF16NSRange: match.range(at: submatchIndex))
let submatchString = String(self[submatchRange])
submatchStrings.append(submatchString)
}
newString.replaceSubrange(matchRange, with: block(matchString, submatchStrings))
}
return newString
}
/// Find all matches of the specified regex.
///
/// - Parameters:
/// - regex: the regex to use.
/// - options: the regex options.
///
/// - Returns: the requested matches.
///
public func matches(regex: String, options: NSRegularExpression.Options = []) -> [NSTextCheckingResult] {
let regex = try! NSRegularExpression(pattern: regex, options: options)
let fullRange = NSRange(location: 0, length: utf16.count)
return regex.matches(in: self, options: [], range: fullRange)
}
/// Replaces all matches of a given RegEx, with a template String.
///
/// - Parameters:
/// - regex: the regex to use.
/// - template: the template string to use for the replacement.
/// - options: the regex options.
///
/// - Returns: a new string after replacing all matches with the specified template.
///
public func replacingMatches(of regex: String, with template: String, options: NSRegularExpression.Options = []) -> String {
let regex = try! NSRegularExpression(pattern: regex, options: options)
let fullRange = NSRange(location: 0, length: utf16.count)
return regex.stringByReplacingMatches(in: self,
options: [],
range: fullRange,
withTemplate: template)
}
}