字符串正则匹配

2019-10-08  本文已影响0人  微凉初夏

APP中经常需要做正则匹配,如下是一个正则匹配的方法类封装

1. 基本方法
class XJJMatching {
//org --> Original, nor --> Normative//
class func predicate_match(_ org: String, nor: String) -> Bool {
    let predicate = NSPredicate(format: "SELF MATCHES %@", nor)
    return predicate.evaluate(with:org)
}

class func regex_match(_ org: String, nor: String) -> Bool {
    var isMatch: Bool = false
    do {
        let regex = try NSRegularExpression(pattern: nor, options: .caseInsensitive)
        let results = regex.matches(in: org, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, org.count))
        if results.count > 0 {
            isMatch = true
        }else {
            deprint("not match!")
        }
    } catch {
        deprint("error!")
    }
    
    return isMatch
}
}
2. 常用正则表达式
struct ExpEmail {
static let general = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9]+\\.[A-Za-z]{1,4}$"
}

struct ExpPassword {
//有数字和字母,至少有一个数字和字母
/*
 ^ 匹配一行的开头位置
 (?![0-9]+$) 预测该位置后面不全是数字
 (?![a-zA-Z]+$) 预测该位置后面不全是字母
 [0-9A-Za-z] {6,10} 由6-10位数字或这字母组成
 $ 匹配行结尾位置
 */
static let least_one_letter_number = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$"
static let letter_number = "^[A-Za-z0-9]+$"
}

struct ExpPhone {
static let general = "^[0-9+]{1,32}$"
static let china = "^(13[0-9]{9})|(14[57][0-9]{8})|(15([0-3]|[5-9])[0-9]{8})|(166[0-9]{8})|(17(0|[6-8])[0-9]{8})|(18[0-9]{9})|((19[0-9])[0-9]{8})$"
static let china_mobile = "(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)"
static let china_unicom = "(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)"
static let china_telecom = "(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)"
}

struct ExpWebsite {
static let general = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"
}

struct ExpText {
static let title = "^[A-Za-z0-9\\u4e00-\\u9fa5]+$" // 一般的名称、标题(只含有中文、字母、数字)

// 特殊文字(含有中文、字母、数字,以及其他一些特殊符号)
// 特殊符号可根据需要更改
static let description = "^[a-zA-Z0-9\\u4E00-\\u9FA5\\u278b-\\u2792,.;:?!。,!?-_:;\"\"“”、‘’''()() ]+$"
}

struct ExpMac {
static let mac = "^[0-9A-Fa-f:]+$"
}
3. 字符串方法扩展
extension String {

func isPhoneNumber() -> Bool {
    return XJJMatching.regex_match(self, nor: ExpPhone.china)
}

func isNormalTitle() -> Bool {
    return XJJMatching.predicate_match(self, nor: ExpText.title)
}

func isNormalDescription() -> Bool {
    return XJJMatching.predicate_match(self, nor: ExpText.description)
}

func isMac() -> Bool {
    return XJJMatching.predicate_match(self, nor: ExpMac.mac)
}

func isPsw() -> Bool {
    return XJJMatching.predicate_match(self, nor: ExpPassword.letter_number)
}
}
上一篇下一篇

猜你喜欢

热点阅读