forked from twostraws/Unwrap
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathString-Regex.swift
More file actions
28 lines (23 loc) · 932 Bytes
/
String-Regex.swift
File metadata and controls
28 lines (23 loc) · 932 Bytes
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
//
// RegexHelpers.swift
// Unwrap
//
// Created by Paul Hudson on 09/08/2018.
// Copyright © 2018 Hacking with Swift.
//
import Foundation
extension String {
/// Replaces only one regex match with a replacement string. Used when generating errors, because we want to do things like remove only one quote mark.
func replacingOne(of search: String, with replacement: String) -> String {
let regex = NSRegularExpression(search)
let matches = regex.matches(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count)).shuffled()
if let match = matches.first {
let range = match.range(at: 1)
if let swiftRange = Range(range, in: self) {
let textMatch = self[swiftRange]
return self.replacingOccurrences(of: textMatch, with: replacement, options: [], range: swiftRange)
}
}
return self
}
}