Last active
December 24, 2019 05:21
-
-
Save monsoir/61acaff7a1119d5ab4e3b67689adbf32 to your computer and use it in GitHub Desktop.
String regex
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
extension String { | |
/// 是否为合法邮箱地址 | |
var isValidEmail: Bool { | |
// https://stackoverflow.com/a/41782027/5211544 | |
let firstPart = "[A-Z0-9a-z]([A-Z0-9a-z._%+-]{0,30}[A-Z0-9a-z])?" | |
let serverPart = "([A-Z0-9a-z]([A-Z0-9a-z-]{0,30}[A-Z0-9a-z])?\\.){1,5}" | |
let regex = "\(firstPart)@\(serverPart)[A-Za-z]{2,8}" | |
let predicate = NSPredicate(format: "SELF MATCHES %@", regex) | |
return predicate.evaluate(with: self) | |
} | |
/// 将 hex 字符组成的字符串按照字面值转换为 16 进制数据 | |
var literalAsBytes: [UInt8] { | |
guard count % 2 == 0 else { | |
fatalError("count of \(self) must be even.") | |
} | |
var result = [UInt8]() | |
for i in 0 ..< (count / 2) { | |
let start = index(startIndex, offsetBy: 2 * i) | |
let end = index(start, offsetBy: 1) | |
let temp = String(self[start...end]) | |
let piece = UInt8(temp, radix: 16)! | |
result.append(piece) | |
} | |
return result | |
} | |
/// 将 hex 字符组成的字符串按照字面值转换为二进制数据 | |
var binaryData: Data { | |
return Data(literalAsBytes) | |
} | |
} |
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
/// 打 call | |
func call() -> Bool { | |
let result = components(separatedBy: CharacterSet.init(charactersIn: "0123456789-+()").inverted).joined(separator: "") | |
if let url = URL(string: "tel:\(result)"), | |
UIApplication.shared.canOpenURL(url) { | |
UIApplication.shared.open(url, options: [:], completionHandler: nil) | |
return true | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment