Created
April 13, 2018 09:35
-
-
Save jbarros35/65bfa62c302b11992a64c5496e358813 to your computer and use it in GitHub Desktop.
Swift flatmap and regex matches
This file contains hidden or 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 matches(for regex: String, in text: String) -> [String] { | |
do { | |
let regex = try NSRegularExpression(pattern: regex) | |
let results = regex.matches(in: text, | |
range: NSRange(text.startIndex..., in: text)) | |
return results.map { | |
String(text[Range($0.range, in: text)!]) | |
} | |
} catch let error { | |
print("invalid regex: \(error.localizedDescription)") | |
return [] | |
} | |
} | |
let stringS = ["RLRLRL","RRLL","LLRRRLRLR","RRRLLLLRLRLR"] | |
.flatMap({ | |
matches(for: "(RL)|(LR)|(R{2}L{2})", in: $0) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment