Golang 正则匹配身份证和手机号

2023-03-12  本文已影响0人  捡书
import (
    idvalidator "github.com/guanguans/id-validator"
)

func HasIDCard(str string) bool {
    reg := regexp.MustCompile(`(\d{17}[0-9Xx])`)
    params := reg.FindAllString(str, -1)
    for i := 0; i < len(params); i++ {
        if idvalidator.IsStrictValid(params[i]) {
            return true
        }
    }
    return false
}


func HasPhoneNumber(str string) bool {
    str = strings.TrimSpace(str)
    if len(str) < 11 {
        return false
    }
    if len(str) == 11 {
        return validatePhoneNum(str)
    } else {
        reg := regexp.MustCompile(`[^a-zA-Z0-9][86]?((13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8})[^a-zA-Z0-9]`)
        params := reg.FindAllString(str, -1)
        for _, param := range params {
            if validatePhoneNum(param) {
                return true
            }
        }
    }
    return false
}

func validatePhoneNum(mobileNum string) bool {
    reg := regexp.MustCompile(`\D`)
    mobileNum = reg.ReplaceAllString(mobileNum, "")
    if strings.HasPrefix(mobileNum, "86") {
        mobileNum = strings.Replace(mobileNum, "86", "", 1)
    }
    reg = regexp.MustCompile(`^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$`)
    return reg.MatchString(mobileNum)
}
上一篇下一篇

猜你喜欢

热点阅读