Skip to content

Instantly share code, notes, and snippets.

@leilee
Last active November 14, 2017 21:41
Show Gist options
  • Save leilee/8995bc5b0934117a217e52276b8d9510 to your computer and use it in GitHub Desktop.
Save leilee/8995bc5b0934117a217e52276b8d9510 to your computer and use it in GitHub Desktop.
Swift regex matches
//: Playground - noun: a place where people can play
import Foundation
extension String {
func matchs(for regex: String) -> [String] {
let regex = try! NSRegularExpression(pattern: regex, options: [])
let matchs = regex.matches(in: self, options: [], range: NSRange(location: 0, length: characters.count))
return matchs.map { (self as NSString).substring(with: $0.range) }
}
}
let pattern = "(folder|doc|spreadsheet|sheet)/([0-9a-zA-Z]{16})"
let testDoc = "https://shimo.im/doc/BotXP1SpKWYEwISo"
print(testDoc.matchs(for: pattern)) // ["doc/BotXP1SpKWYEwISo"]
let testFolder = "https://shimo.im/folder/FE6BdL0jac4m7G7Z/"
print(testFolder.matchs(for: pattern)) // ["folder/FE6BdL0jac4m7G7Z"]
let testSheet = "https://shimo.im/sheet/LzlPT9jCrLAGI1MI"
print(testSheet.matchs(for: pattern)) // ["sheet/LzlPT9jCrLAGI1MI"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment