【问题标题】:Regular expression to replace first 4 characters替换前 4 个字符的正则表达式
【发布时间】:2021-02-01 10:10:43
【问题描述】:

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

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

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

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

【问题讨论】:

  • 但是为什么你需要一个正则表达式呢?
  • 使用正则表达式,您可以检查不超过 x char 之前:(?<!.{4}). and replace with *
  • 这不是所选答案的重复@WiktorStribiżew
  • @bobblebubble,除非您可以解释为什么正则表达式是您问题的关键部分,或者以其他方式有意义地不同,否则它重复的。请阅读How to Ask

标签: java regex


【解决方案1】:

这是一个使用 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,字符串重复需要 a different approach

【讨论】:

    【解决方案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 -> ***
    }
    

    【讨论】:

      【解决方案3】:

      简单使用

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

      regex proof

      解释

      --------------------------------------------------------------------------------
        (?<=                     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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-13
        • 1970-01-01
        • 1970-01-01
        • 2015-11-30
        • 1970-01-01
        相关资源
        最近更新 更多