Skip to content

Instantly share code, notes, and snippets.

@klein-artur
Last active June 15, 2021 06:25
Show Gist options
  • Save klein-artur/0dfe79a3a157d8964c281be625e7cde9 to your computer and use it in GitHub Desktop.
Save klein-artur/0dfe79a3a157d8964c281be625e7cde9 to your computer and use it in GitHub Desktop.
Some String extensions for regex
struct RgxResult {
private let textCheckingResult: NSTextCheckingResult
private let baseString: String
init(_ result: NSTextCheckingResult, _ baseString: String) {
self.textCheckingResult = result
self.baseString = baseString
}
}
extension String {
var rgx: NSRegularExpression? {
try? NSRegularExpression(pattern: self, options: [])
}
func find(rgx pattern: String) -> [RgxResult] {
pattern.rgx?.matches(in: self, options: [], range: 0<!>self.count)
.map {
RgxResult(
$0,
self
)
} ?? []
}
func replace(rgx pattern: String, with template: String) -> String {
let mutatingString = NSMutableString(string: self)
pattern.rgx?.replaceMatches(in: mutatingString, options: [], range: 0<!>self.count, withTemplate: template)
return mutatingString as String
}
}
extension RgxResult {
subscript(index: Int) -> String? {
guard textCheckingResult.range(at: index).location != NSNotFound else {
return nil
}
return String(baseString[Range(textCheckingResult.range(at: index), in: baseString)!])
}
}
extension Int {
static func <!> (left: Int, right: Int) -> NSRange {
NSRange(location: left, length: right - left)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment