java - 在 '@'之前屏蔽电子邮件中的中间字符

标签 java regex kotlin regex-lookarounds

我只想显示电子邮件的前两个字符和后两个字符,如下所示:

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/

相关文章:

java.sql.SQLException : Before/after start of result set

java - 在 Google App-Engine JAVA 中将文本转换为字符串,反之亦然

java - session 变量存储在 Java Web 应用程序中的位置

Kotlin 协程 "happens-before"保证?

java - android studio 3.6.1调试找不到局部变量

java - 从 Activity B 返回到 Activity A 的 fragment

Java 正则表达式 : how to capture multiple matches in the same line

php - 如何使用正则表达式删除没有数字和扩展名的任何内容?

php - 如何查找字符串是否包含所有英文字母或阿拉伯文字母

postgresql - Kotlin 中的 JdbcTemplate IN 子句