Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Created May 20, 2020 23:00
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 robertmryan/138ffea5603625830d0970b3022fefdf to your computer and use it in GitHub Desktop.
Save robertmryan/138ffea5603625830d0970b3022fefdf to your computer and use it in GitHub Desktop.
extension String {
func matches(of regex: String, options: NSRegularExpression.Options = []) throws -> [String] {
try NSRegularExpression(pattern: regex, options: options)
.matches(in: self, range: NSRange(startIndex..., in: self))
.compactMap { Range($0.range, in: self) }
.map { String(self[$0]) }
}
}
@robertmryan
Copy link
Author

Then you can do things like:

let string = "There are 42 apples and 13 oranges."
let results = try string.matches(of: #"\d+"#)
print(results) // ["42", "13"]

or, the following will do a case insensitive search

let result = try string.matches(of: "Rob(ert)? Ryan", options: .caseInsensitive)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment