swift的正则表达式(NSRegularExpression)
by 伍雪颖
import UIKit
class ViewController:
UIViewController {
override
func viewDidLoad() {
super.viewDidLoad()
let mailPattern =
"^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
let matcher =
RegexHelper(mailPattern)
let maybeMailAddress =
"[email protected]"
if matcher.match(maybeMailAddress)
{
println("valid email")
}
}
struct RegexHelper {
let regex:
NSRegularExpression?
init(_
pattern: String) {
var error:
NSError?
regex =
NSRegularExpression(
pattern: pattern,
options: .CaseInsensitive,
error: &error)
}
func match(input:
String) ->
Bool {
if
let matches =
regex?.matchesInString(input,
options: nil,
range: NSMakeRange(0,
count(input))) {
return matches.count
> 0
} else {
return
false
}
}
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-03 21:54:32