Created
May 18, 2022 03:24
-
-
Save yoxisem544/a8e44c6f425aa73614a5eeaedd079460 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import Foundation | |
enum SteakerRegex { | |
case email | |
case password | |
case address(String) | |
case chineseCharacter | |
var rawRegex: String { | |
switch self { | |
case .email: | |
return #"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$"# | |
case .password: | |
return #"(?=.*\d)(?=.*[A-Za-z]).{8,}"# | |
case .address(let addressRegex): | |
return addressRegex | |
case .chineseCharacter: | |
// https://stackoverflow.com/questions/11897531/detecting-if-nsstring-contains-chinese-characters/11898220#11898220 | |
return #"\p{script=Han}"# | |
} | |
} | |
} | |
extension String { | |
func validate(regex: SteakerRegex) -> Bool { | |
!match(regex: regex.rawRegex).isEmpty | |
} | |
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 [] | |
} | |
} | |
/// To check if this string is contains only chinese characters. | |
/// Empty string will return false. | |
func checkIfPureChineseString() -> Bool { | |
guard !isEmpty else { return false } | |
let originCharacterCount = self.count | |
let chineseCharacterCount = self.match(regex: SteakerRegex.chineseCharacter.rawRegex).count | |
return originCharacterCount == chineseCharacterCount | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment