Skip to content

Instantly share code, notes, and snippets.

@TucoBZ
Last active September 22, 2017 22:53
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 TucoBZ/2981f83dfc66e2353044d7c6f6c70f62 to your computer and use it in GitHub Desktop.
Save TucoBZ/2981f83dfc66e2353044d7c6f6c70f62 to your computer and use it in GitHub Desktop.
[Swift] - String Regex Match and Email Check
//: Playground - noun: a place where people can play
import Foundation
extension String {
/// Return all matches substrings from this string using this regex
///
/// - Parameter regex: A string Regex to match
/// - Returns: array of substrings that matches this regex
func matches(from regex: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = self as NSString
let results = regex.matches(in: self, range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range)}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
/// Check if this string is an email
var isAnEmail: Bool {
return self.matches(from: "^[A-Z0-9a-z._%+-]+\\@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$").count == 1
}
}
let newEmail = "glauber@gmail.com"
print(newEmail.isAnEmail)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment