all. I want to mask email and am having a little problem.
My code
val email = [email protected]
val p = """^([^@]{2})([^@] )""".toRegex()
val result = email.replace(p) {
it.groupValues[1] "*".repeat(it.groupValues[2].length)
}
expected result : mask with * for first two letters && first four letters after @
lu********@****l.com
current result : can mask before @ but not after it
lu********@gmail.com
How can I mask the first 4 letters after @?
CodePudding user response:
For anyone who will see this post later, here I share my code.
Email Mask : lu********@****l.com
val regex = """^([^@]{2})([^@] )([^@]{0}@)([^@]{4})""".toRegex()
val emailMask = args.biometricOtp.otpData.replace(regex) {
it.groupValues[1] "*".repeat(it.groupValues[2].length)
it.groupValues[3] "*".repeat(it.groupValues[4].length) }
Phone number Mask : 82103*******
val regex = """([^@]{5})([^@] )""".toRegex()
val smsMask = args.biometricOtp.otpData.replace(regex) {
it.groupValues[1] "*".repeat(it.groupValues[2].length) }
CodePudding user response:
You can replace all chars with *
that match the following pattern:
(?:\G(?!^)|(?<=^[^@]{2}|@))[^@](?!\.[^.] $)
See the regex demo. Details:
(?:\G(?!^)|(?<=^[^@]{2}|@))
- match@
(with@
), or start of string and any two chars other than@
(with(?<=^[^@]{2}
), or the end of the previous successful match (with\G(?!^)
)[^@]
- any one char other than a@
(?!\.[^.] $)
- that is not immediately followed with a.
and then one or more chars other than.
till the end of string.
See the Kotlin demo:
val regex = """(?:\G(?!^)|(?<=^[^@]{2}|@))[^@](?!\.[^.] $)""".toRegex()
val email = "[email protected]"
val emailMask = email.replace(regex, "*")
print(emailMask)
// => lu********@****l.com