Swift 重构:正则表达式/NSRegularExpression 过滤文本

·  阅读 171

思路来源:

开发中遇到复杂的字符匹配,正则表达式是最常用的实现方式,每次从头写一堆重复/相似的代码就很令人烦躁的,随想重构一下使用方法,方便以后使用,最终一行调用即可;

//定义常见匹配模式
public extension NSRegularExpression{

    ///正则匹配模式
    enum Pattern: String {

        ///汉字匹配表达式
        case hanzi = "[\\u4E00-\\u9FA5]+"

        ///非汉字匹配表达式
        case nonHanzi = "[^\\u4E00-\\u9FA5]+"

        ///英文字母匹配表达式
        case alphabet = "[a-zA-Z]+"

        ///非英文字母匹配表达式
        case nonAlphabet = "[^a-zA-Z]+"

        ///数字匹配表达式
        case number = "[0-9]+"

        ///非数字匹配表达式
        case nonNumber = "[^0-9]+"

        ///浮点数匹配表达式
        case float = "[0-9.]+"

        ///非浮点数匹配表达式
        case nonFloat = "[^0-9.]+"
    }
}
复制代码

Example

核心方法 matchTuple 返回元祖(NSRange,String)数组;

let input = "My name is 泰勒 88.8, My name is 斯威夫特 99.9"

let tuples = NSRegularExpression.matchTuple(NSRegularExpression.Pattern.alphabet.rawValue, input: input)
DDLog(tuples)//[({0, 2}, "My"), ({3, 4}, "name"), ({8, 2}, "is"), ({20, 2}, "My"), ({23, 4}, "name"), ({28, 2}, "is")]

        
let dic = NSRegularExpression.matchDic(NSRegularExpression.Pattern.alphabet.rawValue, input: input)
DDLog(dic)// ["{28, 2}": "is", "{23, 4}": "name", "{8, 2}": "is", "{0, 2}": "My", "{3, 4}": "name", "{20, 2}": "My"]
///匹配汉字
let result = NSRegularExpression.matchTuple2(.hanzi, input: input)
//**[({11, 2}, "泰勒"), ({31, 4}, "斯威夫特")]**

///匹配非汉字
let result1 = NSRegularExpression.matchTuple2(.nonHanzi, input: input)
///匹配数字
let result2 = NSRegularExpression.matchTuple2(.number, input: input)
///匹配非数字
let result3 = NSRegularExpression.matchTuple2(.nonNumber, input: input)
///匹配浮点数字
let result4 = NSRegularExpression.matchTuple2(.float, input: input)
///匹配非浮点数字
let result5 = NSRegularExpression.matchTuple2(.nonFloat, input: input)
///匹配大小写字母
let result6 = NSRegularExpression.matchTuple2(.alphabet, input: input)
///匹配非大小写字母
let result7 = NSRegularExpression.matchTuple2(.nonAlphabet, input: input)

DDLog(result)
//**[({11, 2}, "泰勒"), ({31, 4}, "斯威夫特")]**
DDLog(result1)
//**[({0, 11}, "My name is "), ({13, 18}, " 88.8, My name is "), ({35, 5}, " 99.9")]**
DDLog(result2)
//**[({14, 2}, "88"), ({17, 1}, "8"), ({36, 2}, "99"), ({39, 1}, "9")]**
DDLog(result3)
//**[({0, 14}, "My name is 泰勒 "), ({16, 1}, "."), ({18, 18}, ", My name is 斯威夫特 "), ({38, 1}, ".")]**
DDLog(result4)
//**[({14, 4}, "88.8"), ({36, 4}, "99.9")]**
DDLog(result5)
//**[({0, 14}, "My name is 泰勒 "), ({18, 18}, ", My name is 斯威夫特 ")]**
DDLog(result6)
//**[({0, 2}, "My"), ({3, 4}, "name"), ({8, 2}, "is"), ({20, 2}, "My"), ({23, 4}, "name"), ({28, 2}, "is")]**
DDLog(result7)
//**[({2, 1}, " "), ({7, 1}, " "), ({10, 10}, " 泰勒 88.8, "), ({22, 1}, " "), ({27, 1}, " "), ({30, 10}, " 斯威夫特 99.9")]**
   
复制代码

源码

github

分类:
iOS
标签:
收藏成功!
已添加到「」, 点击更改