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 = "lesvio@qq.com"
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
}
}
}
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 = "lesvio@qq.com"
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
}
}
}
}