Skip to content

Instantly share code, notes, and snippets.

@kmussel
Created February 8, 2017 16:16
Show Gist options
  • Save kmussel/963cb5be164140d3a6e5e41b4a35fde7 to your computer and use it in GitHub Desktop.
Save kmussel/963cb5be164140d3a6e5e41b4a35fde7 to your computer and use it in GitHub Desktop.
parse host file using swift regex
func captureGroups(withRegex pattern: String, with hosts:String) -> [String] {
var matches : [String] = []
var regex: NSRegularExpression
do {
regex = try NSRegularExpression(pattern: pattern, options: [.caseInsensitive, .anchorsMatchLines])
} catch {
return matches
}
regex.enumerateMatches(in: hosts, options: [], range: NSRange(location: 0, length: hosts.characters.count)) { (result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, _) in
if let range = result?.rangeAt(1) {
matches.append((hosts as NSString).substring(with: range))
}
if let range = result?.rangeAt(3) {
matches.append((hosts as NSString).substring(with: range))
}
}
return matches
}
let url = Bundle.main.url(forResource: "hosts", withExtension: "")
do {
if let path = url?.path {
let hosts = try String(contentsOfFile: path, encoding: .utf8)
let groups = captureGroups(withRegex: "^(?!#)([^\\s]*)(\\s+)(.*)$", with:hosts)
print(groups)
}
print(hosts)
} catch(let er) {
print(er)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment