正则表达式替换前4个字符

3

我正在尝试编写一个正则表达式,将字符串的前4个字符替换为*

例如,对于输入123456,预期输出为****56

如果输入长度小于4,则只返回*

例如,如果输入是123,则返回值必须为***


4
为什么你需要使用正则表达式来做这件事情? - anubhava
1
使用正则表达式,您可以检查前面不超过x个字符:(?<!.{4}).并替换为* - bobble bubble
这不是所选答案的重复@WiktorStribiżew。 - bobble bubble
@bobblebubble,除非你能解释为什么正则表达式是你问题的关键部分,或者以其他方式有意义地不同,否则它是一个重复的问题。请阅读[ask]。 - Chris
3个回答

3

这里有一个简单的解决方案,使用自 开始可用的 String#repeat(int)。不需要使用正则表达式。

static String hideFirst(String string, int size) {
    return size < string.length() ?                     // if string is longer than size
            "*".repeat(size) + string.substring(size) : // ... replace the part
            "*".repeat(string.length());                // ... or replace the whole
}

String s1 = hideFirst("123456789", 4);    // ****56789
String s2 = hideFirst("12345", 4);        // ****5
String s3 = hideFirst("1234", 4);         // ****
String s4 = hideFirst("123", 4);          // ***
String s5 = hideFirst("", 4);             // (empty string)
  • 您可能希望将星号(或任何字符)传递给该方法以获得更多的控制
  • 您可能希望处理null(返回null/抛出NPE/抛出自定义异常...)
  • 对于较低版本的Java,您需要另一种方法来进行字符串重复。

2
您可以尝试使用以下正则表达式捕获前4个字符。
(.{0,4})(.*)

现在,您可以使用Pattern、Matcher和String类来实现您想要的功能。
Pattern pattern = Pattern.compile("(.{0,4})(.*)");
Matcher matcher = pattern.matcher("123456");

if (matcher.matches()) {
    String masked = matcher.group(1).replaceAll(".", "*");
    String result = matcher.replaceFirst(masked + "$2");

    System.out.println(result);
    // 123456 -> ****56
    // 123 -> ***
}

0

只需使用

String masked = string.replaceAll("(?<=^.{0,3}).", "*");

请查看正则表达式验证

解释

--------------------------------------------------------------------------------
  (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
    ^                        the beginning of the string
--------------------------------------------------------------------------------
    .{0,3}                   any character except \n (between 0 and 3
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  .                        any character except \n

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接