Skip to content

Instantly share code, notes, and snippets.

@jbarros35
Created April 13, 2018 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbarros35/65bfa62c302b11992a64c5496e358813 to your computer and use it in GitHub Desktop.
Save jbarros35/65bfa62c302b11992a64c5496e358813 to your computer and use it in GitHub Desktop.
Swift flatmap and regex matches
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