模式匹配

模式匹配特性类似于正则表达式的匹配

// 重载 ~= ,使它接受一个 NSRegularExpression 作为模式,去匹配输入的 String

func ~=(pattern: NSRegularExpression, input: String) -> Bool {

return pattern.numberOfMatches(in: input,

options: [],

range: NSRange(location: 0, length: input.characters.count)) > 0

}

// 为了简便,再添加一个将字符串转换为 NSRegularExpression 的操作符

// 定义“前位”操作符

prefix operator ~/

// 定义操作符

prefix func ~/(pattern: String) throws -> NSRegularExpression  {

do {

return try NSRegularExpression(pattern: pattern, options: [])

}catch _ {

assertionFailure()

return NSRegularExpression()

}

}

let contact = ("http://onevcat.com", "[email protected]")

let mailRegx: NSRegularExpression

let siteRegx: NSRegularExpression

mailRegx = try ~/"^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"

siteRegx = try ~/"^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"

switch contact {

case (siteRegx, mailRegx): print("同时拥有有效的网站和邮箱")  // 这里输出

case (_, mailRegx):print("只拥有有效的邮箱")

case (siteRegx, _):print("只拥有有效的网站")

default:print("嘛都没有")

}

你可能感兴趣的:(模式匹配)