贡献者:赵大财
博客:https://my.oschina.net/zhaodacaiGitHub:https://github.com/zhaodacai
邮箱: zhaodacai@yeah.com QQ:327532817
=============================
先直接来代码:
fileprivate func check(str: String) { do { let pattern = "[^a-z]" let regex = try NSRegularExpression(pattern: pattern,options: .caseInsensitive) let dacaiRange = NSMakeRange(0,str.characters.count) //匹配到的个数 let resa = regex.numberOfMatches(in: str,options: [],range: dacaiRange) print(resa) //匹配第一个结果集 guard let resb = regex.firstMatch(in: str,range: dacaiRange) else { return } print((str as Nsstring).substring(with: resb.range)) //第一个结果的range print(regex.rangeOfFirstMatch(in: str,options:[],range: dacaiRange).location) //匹配全部 let resc = regex.matches(in: str,options: NSRegularExpression.MatchingOptions(rawValue: 0),range:dacaiRange) for checkingRes in resc { print(checkingRes.range.location,checkingRes.range.length) print((str as Nsstring).substring(with: checkingRes.range)) } //替换 let newStr = regex.stringByReplacingMatches(in: str,range: dacaiRange,withTemplate: "-e-") print(newStr) } catch { print(error) }
NSRegularExpression.Options caseInsensitive 不区分大小写 allowCommentsAndWhitespace允许注释和空白 ignoreMetacharacters 忽略字符 dotMatchesLineseparators 匹配行空格符 anchorsMatchLines 锚配线 useUnixLineseparatorsUnix行分隔符 useUnicodeWordBoundariesUnicode字边界