Created
November 19, 2019 21:32
-
-
Save sstadelman/11bd7141222dbcf3942f343b756b24bc to your computer and use it in GitHub Desktop.
Matcher to find mustache placeholder keys and replacement ranges
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
extension Array where Element == NSRange { | |
func maxRange() -> Int { | |
return self.reduce(0) { (prev, next) in | |
let maxNext = NSMaxRange(next) | |
return Swift.max(prev, maxNext) | |
} | |
} | |
} | |
extension String { | |
private static let mustacheRegex = try! NSRegularExpression(pattern: #"\{\{?(?<mustache>(#[a-z])?[a-z]+.[a-z])*\}?\}"#, options: []) | |
private static let mustacheKeyname = "mustache" | |
func mustachePlaceholders() -> [(String, NSRange)] { | |
var shouldStop = false | |
var placeholders: [(keyname: String, replacementRange: NSRange)] = [] | |
var counterIndex: Int = 0 | |
while !shouldStop { | |
guard counterIndex < self.count else { shouldStop = true; break } | |
if let match = String.mustacheRegex.firstMatch(in: self, options: [], range: NSRange(counterIndex..<self.count)) { | |
let range = match.range(withName: String.mustacheKeyname) | |
if range.location != NSNotFound { | |
placeholders.append((keyname: NSString(string: self).substring(with: range), replacementRange: match.range)) | |
} | |
} else { shouldStop = true; break } | |
counterIndex = placeholders.map({ $0.replacementRange }).maxRange() + 1 | |
} | |
return placeholders | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment