Swift 正则方式截取单词

作品链接:
http://www.jianshu.com/users/1e0f5e6f73f6/top_articles

let str = "Probably at least one of the constraints in the following list is one you don't want"
         
//.匹配除换行符以外的任意字符 *重复零次或更多次 +重复一次或更多次 ?重复零次或一次
        do{
            // 1.创建规则
            let pattern1 = "[a-z]"
            let pattern2 = "[A-Z]"
            let pattern3 = "[\\s]"
            //多个规则之间使用 | 符号连接
            let pattern =  pattern1 + "|" + pattern2 + "|" + pattern3
            // 2.创建正则表达对象
            let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
            
            // 3.开始匹配
            let res = regex.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, str.characters.count))
            for checkingRes in res {
                // 截取匹配的字符串
                print((str as NSString).substringWithRange(checkingRes.range))
            }
        }catch{
            print(error)
        }

你可能感兴趣的:(Swift 正则方式截取单词)