屏蔽Swift字符串中的字符

时间:2019-07-10 21:41:24

标签: swift string swift5

在Swift 5中,是否存在一种规范的方法来屏蔽掉一个Swift String中不包含(完全匹配)第二个“ masking”字符串中的所有字符?也许使用地图和/或过滤器?

例如maskString(“ abcdba”,withMask:“ ab”)->“ abba”

maskString(“ abcdba”,withMask:“ ab”,replaceWith:“?”)->“ ab ?? ba”

1 个答案:

答案 0 :(得分:3)

replacingOccurrences与以下选项一起使用:

let str = "abcdba"

let result = str.replacingOccurrences(of: "[^ab]", with: "", options: .regularExpression)

print(result)  //"abba"

或者您可以定义如下函数:

func maskString (
    _ str: String,
    withMask mask: String ,
    replaceWith replacement: String = ""
    ) -> String {
    return str
        .replacingOccurrences(of: "[^\(mask)]",
            with: replacement,
            options: .regularExpression)
}

并像这样使用它:

maskString("abcdba", withMask: "ab")                    //"abba"
maskString("abcdba", withMask: "ab" , replaceWith: "?") //"ab??ba"