屏蔽 Swift 字符串中的字符
Masking characters in a Swift string
在 Swift 5 中是否有一种规范的方法来屏蔽一个 Swift 字符串中不包含(完全匹配)在第二个 "masking" 字符串中的所有字符?也许使用 map and/or 过滤器?
例如maskString("abcdba", withMask: "ab") -> "abba"
或
maskString("abcdba", withMask: "ab" , replaceWith: "?") -> "ab??ba"
使用 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"
在 Swift 5 中是否有一种规范的方法来屏蔽一个 Swift 字符串中不包含(完全匹配)在第二个 "masking" 字符串中的所有字符?也许使用 map and/or 过滤器?
例如maskString("abcdba", withMask: "ab") -> "abba"
或
maskString("abcdba", withMask: "ab" , replaceWith: "?") -> "ab??ba"
使用 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"