欢迎加入我个人维护QQ群:379069176
PS:定期分享干货
首先引入这个小文件:
将字符串用MD5加密
extension String {
var MD5: String! {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
let hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.dealloc(digestLen)
return hash as String
}
}
把Data用MD5加密
/// NSData
extension NSData {
var dataToMD5String: String! {
let digestLength = Int(CC_MD5_DIGEST_LENGTH)
let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLength)
CC_MD5(self.bytes, CC_LONG(self.length), md5Buffer)
let output = NSMutableString(capacity: Int(CC_MD5_DIGEST_LENGTH * 2))
for i in 0..<digestLength {
output.appendFormat("%02x", md5Buffer[i])
}
return String(format: output as String)
}
}
正则匹配
/// 正则匹配
enum RegexType: String {
case Mail
case URL
case Image
var regexText: String {
switch self {
case .Mail:
return "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?"
case .URL:
return "(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?"
case .Image:
return "([a-zA-z]+://[^\\s]*)+.(?:jpg|png|gif|jpe?g)"
}
}
}
// 方法返回bool类型,判断是否符合匹配
func regexMatch(input: String, type: RegexType) -> Bool {
let nsText = input as NSString
let regex = try! NSRegularExpression(pattern: type.regexText, options: [.CaseInsensitive, .DotMatchesLineSeparators])
let matches = regex.matchesInString(input, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, nsText.length))
if matches.count > 0 {
return true
} else {
return false
}
}