标签:
通常用一个常用的正则类
class Regex { let internalExpression: NSRegularExpression let pattern: String init(_ pattern: String) { self.pattern = pattern var error: NSError? self.internalExpression = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: &error)! } func test(input: String) -> Array<String>{ let matches = self.internalExpression.matchesInString(input, options: nil, range:NSMakeRange(0, countElements(input))) as Array<NSTextCheckingResult> if (matches.count>0) { var values:Array<String> = [] for result in matches { for i in 0...(result.numberOfRanges-1) { let range = result.rangeAtIndex(i) var nsinput = input as NSString values += [nsinput.substringWithRange(NSRange(location: range.location,length: range.length))] } } //println(values) return values }else{ return [] } } }
正则表达是 \d 在双引号中 要写成 \\d ,如 取5个数字 "\\d{5}" .
例如取3-30个字符(包含数字 或者字母 或 - )可以写成
var matchResult = Regex("[\\d\\w-]{2,30}").test(domainInput.text) if !matchResult.isEmpty { println(matchResult[0]) }
标签:
原文地址:http://www.cnblogs.com/ericjun/p/4260494.html