Created
February 8, 2017 16:16
-
-
Save kmussel/963cb5be164140d3a6e5e41b4a35fde7 to your computer and use it in GitHub Desktop.
parse host file using swift regex
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
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