Skip to content

Instantly share code, notes, and snippets.

@yoxisem544
Created June 17, 2021 03:21
Show Gist options
  • Save yoxisem544/d2d4c84eba016e20cba54dc22b122d6b to your computer and use it in GitHub Desktop.
Save yoxisem544/d2d4c84eba016e20cba54dc22b122d6b to your computer and use it in GitHub Desktop.
extension String {
func match(regex pattern: String) -> [String] {
do {
let text = self
let regex = try NSRegularExpression(pattern: pattern)
let matches = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return matches.flatMap { match in
(0..<match.numberOfRanges).map {
let rangeBounds = match.range(at: $0)
guard let range = Range(rangeBounds, in: text) else {
return ""
}
return String(text[range])
}
}
} catch {
return []
}
}
}
"202107TE".match(regex: #"^\d{6}|(?<=[A-Z])\w\dF?$"#)
"202107XIF".match(regex: #"^\d{6}|(?<=[A-Z])\w\dF?$"#)
"202012CN".match(regex: #"^\d{6}|(?<=[A-Z])\w\dF?$"#)
"202101G2F".match(regex: #"^\d{6}|(?<=[A-Z])\w\dF?$"#)
"202107WMTN1F".match(regex: #"^\d{6}|(?<=[A-Z])\w\dF?$"#)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment