Swift3.0-正则表达式 <待续>

前端之家收集整理的这篇文章主要介绍了Swift3.0-正则表达式 <待续>前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

贡献者:赵大财
博客: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字边界

猜你在找的Swift相关文章