Swift 正则获取字符串中的手机号

let pattern = "(1\\d{10})"
let batteryLevel = "赛风赛风18721710825扽峰等粉丝"

func regexGetSub(pattern:String, str:String) -> String {
    
    var subStr = ""
    let regex = try! NSRegularExpression(pattern: pattern, options:[])
    let matches = regex.matches(in: str, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, str.count))
//    print(matches.count)
    //解析出子串
    
    if let match = matches.first {
        subStr = String(str[Range(match.range(at: 1), in: str)!])
    }
    return subStr
}
var batteryParams = regexGetSub(pattern: pattern, str: batteryLevel)

print(regexGetSub(pattern: pattern, str: batteryLevel))

print结果:
18721710825

我这里的正则比较简单,只识别了1开头并且长度是11位数字。

你可能感兴趣的:(Swift 正则获取字符串中的手机号)