我只想显示电子邮件的前两个字符和后两个字符,如下所示:
Email - 123456789@gmail.com
result - 12*****89@gmail.com
我正在使用此正则表达式将匹配项替换为*-(?<=.{2}).*(?=.{2}@)
。使用的代码段:
String email = "123456789@gamil.com";
System.out.println(email.replaceAll("(?<=.{3}).*(?=.{3}@)", "*"));
// prints - 12**89@gamil.com
// Adds only 2 ** in the middle
// Required * for each replaced character like - 12*****89@gmail.com
即使正则表达式匹配正确的东西,它总是用**
替换中间部分。但是我想要每个字符一个*
。有什么问题以及如何解决?
最佳答案
在Kotlin中使用
val s = "123456789@gmail.com"
val p = """^([^@]{2})([^@]+)([^@]{2}@)""".toRegex()
println(s.replace(p) {
it.groupValues[1] + "*".repeat(it.groupValues[2].length) + it.groupValues[3]
})
参见proof。结果:
12*****89@gmail.com
。模式说明
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
[^@]{2} any character except: '@' (2 times)
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
( group and capture to \2:
--------------------------------------------------------------------------------
[^@]+ any character except: '@' (1 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \2
--------------------------------------------------------------------------------
( group and capture to \3:
--------------------------------------------------------------------------------
[^@]{2} any character except: '@' (2 times)
--------------------------------------------------------------------------------
@ '@'
--------------------------------------------------------------------------------
) end of \3
关于java - 在 '@'之前屏蔽电子邮件中的中间字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64529786/