Last active
September 22, 2017 22:53
-
-
Save TucoBZ/2981f83dfc66e2353044d7c6f6c70f62 to your computer and use it in GitHub Desktop.
[Swift] - String Regex Match and Email Check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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 = "[email protected]" | |
print(newEmail.isAnEmail) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment