在Swift 5中,是否存在一种规范的方法来屏蔽掉一个Swift String中不包含(完全匹配)第二个“ masking”字符串中的所有字符?也许使用地图和/或过滤器?
例如maskString(“ abcdba”,withMask:“ ab”)->“ abba”
或
maskString(“ abcdba”,withMask:“ ab”,replaceWith:“?”)->“ ab ?? ba”
答案 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"