- 正则运算符定义
- 喵神提供的一段定义正则运算符(超级好用!!!),使用范例
if "onev@onevcat.com" =~
"^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$" {
println("有效的邮箱地址")
}
// 输出:
// 有效的邮箱地址
struct RegexHelper {
let regex: NSRegularExpression
init(_ pattern: String) throws {
try regex = NSRegularExpression(pattern: pattern,
options: .CaseInsensitive)
}
func match(inputStr: String) -> Bool {
let matches = regex.matchesInString(inputStr,
options: [],
range: NSMakeRange(0, inputStr.utf16.count))
return matches.count > 0
}
}
infix operator =~ {
associativity none
precedence 130
}
func =~(lhs: String, rhs: String) -> Bool {
do {
return try RegexHelper(rhs).match(lhs)
} catch _ {
return false
}
}
- 下面是一些对String类的扩展(正则相关)
- 返回所有匹配到的字串集合,返回例如: [str1,str2,str3]
/**
返回所有匹配到的字串集合
- parameter pattern: 正则匹配规则
- parameter inputStr: 要匹配的文本
- returns:匹配到的字串集合
*/
func bl_regexWithPattern(pattern : String,
inputStr: String) -> [String] {
// 使用正则表达式一定要加try语句
do {
// - 1、创建规则
let pattern = pattern
// - 2、创建正则表达式对象
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
// - 3、开始匹配
let res = regex.matchesInString(inputStr, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, inputStr.characters.count))
// 输出结果
var subStrArray = [String]()
for checkingRes in res {
let subStr = (inputStr as NSString).substringWithRange(checkingRes.range)
subStrArray.append(subStr)
}
return subStrArray
}
catch {
print(error)
}
//不匹配返回空串
return [String]()
}
- 返回一个字典 key : 匹配到的字串, Value : 匹配到的字串
- 返回例如 : [ keyStr : [NSRange] ]
/// 返回一个字典 key : 匹配到的字串, Value : 匹配到的字串的Range数组
func bl_regexWithPatternAndRange(pattern : String,inputStr: String) -> [[String : [NSRange]]]? {
let strArray = bl_regexWithPattern(pattern, inputStr: inputStr)
var array = [[String : [NSRange]]]()
for subStr in strArray {
var dic = [String : [NSRange]]()
let subStrRangeArray = bl_stringOfRangeArray(subStr, inputStr: inputStr)
dic[subStr] = subStrRangeArray
array.append(dic)
}
return array
}
/// 返回一个数组 Value : 匹配到的字串的Range数组
func bl_stringOfRangeArray(subStr : String, inputStr : String) -> [NSRange]? {
guard inputStr =~ subStr else{
return [NSMakeRange(0, 0)]
}
//设置Range数组
var rangeArray = [NSRange]()
//设置母串
var bigString = inputStr
// - 1、创建规则
let pattern = subStr
var count : Int = 0
do{
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
//获取子串个数
count = regex.numberOfMatchesInString(bigString, options: .ReportProgress, range: NSMakeRange(0, bigString.characters.count))
}catch{
print(error)
}
for i in 0..<count {
var subRange = (bigString as NSString).rangeOfString(pattern)
let cutLoc = subRange.location + subRange.length
let cutLen = bigString.characters.count - cutLoc
bigString = (bigString as NSString).substringWithRange(NSMakeRange(cutLoc, cutLen))
if i > 0 {
let preSubRange = rangeArray[i - 1]
subRange.location = preSubRange.location + preSubRange.length
}
rangeArray.append(subRange)
}
return rangeArray
}