Created
January 4, 2023 01:16
-
-
Save gngrwzrd/f965926595272075305f2a3bdf9fae40 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class NSRegex { | |
private let regex:NSRegularExpression | |
private let subject:String | |
private var matches:[NSTextCheckingResult] = [] | |
init(regex:NSRegularExpression, subject:String) { | |
self.regex = regex | |
self.subject = subject | |
matches = regex.matches(in: subject, range: NSRange(location: 0, length: subject.count)) | |
} | |
func valueForCaptureGroup(at index:Int) -> String? { | |
guard let match = matches.first else { return nil} | |
if index < match.numberOfRanges { return nil } | |
let range = match.range(at: index) | |
return value(forRange: range) | |
} | |
func valueForNamedCaptureGroup(_ named:String) -> String? { | |
guard let match = matches.first else { return nil } | |
let range = match.range(withName: named) | |
return value(forRange: range) | |
} | |
private func value(forRange range:NSRange) -> String? { | |
let startIndex = subject.index(subject.startIndex, offsetBy: range.location) | |
let endIndex = subject.index(startIndex, offsetBy: range.length) | |
let strIndexRange = startIndex..<endIndex | |
return String(subject[strIndexRange]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment