用星号替换字符

Replace characters with asterisk

我在 playground 上有这段代码。

我已经将用户 ID 和电子邮件扩展名分开了。但是我想用 * 更改电子邮件的第一个和最后一个字符之间的字符,除了 .

我正在尝试通过任何电子邮件地址输入使其足够动态。有什么想法吗?谢谢您的意见。

let email = "asdfg.hjkl@gmail.com"
let atSign = email.index(of: "@") ?? email.endIndex
let userID = email[..<atSign]
print(userID + email.suffix(from: atSign))

我只找到了一个迭代解决方案:

let email = "asdfg.hjkl@gmail.com"
let atSign = email.index(of: "@") ?? email.endIndex
let userID = email[..<atSign]
print(userID + email.suffix(from: atSign))


var lastLetterInx = email.index(before:atSign)

var inx = email.startIndex

var result = ""
while(true) {
    if (inx >= lastLetterInx) {
        result.append(String(email[lastLetterInx...]))
        break;
    }

    if (inx > email.startIndex && email[inx] != ".") {
        result.append("*")      
    } else {
        result.append(email[inx])
    }

    inx = email.index(after:inx)
}

print (result)

这是一个使用正则表达式的解决方案,只是多了一行

let email = "asdfg.hjkl@gmail.com"
let atSign = email.index(of: "@") ?? email.endIndex
let userID = email[..<atSign]
let hiddenUserID = userID.replacingOccurrences(of: "(?<!^)[^.]", with: "*", options: .regularExpression)
print(hiddenUserID + email.suffix(from: atSign)) // a****.****@gmail.com