有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (3) 个答案

  1. # 1 楼答案

    您可以将Pattern和Matcher用于这个正则表达式^{},它匹配许多组,如下所示:

    String email = "john.doe@example.en.com";
    Pattern pattern = Pattern.compile("(.)(.*?)(.@.)(.*?)(\\.[^\\.]+)$");
    Matcher matcher = pattern.matcher(email);
    if (matcher.find()) {
        email = matcher.group(1) + matcher.group(2).replaceAll(".", "*") +
                matcher.group(3) + matcher.group(4).replaceAll(".", "*") +
                matcher.group(5);
    }
    

    输出

    j******e@e*********.com
    
  2. # 2 楼答案

    s.replaceAll("(?<=.)[^@\n](?=[^@\n]*?[^@\n]@)|(?:(?<=@.)|(?!^)\\G(?=[^@\n]*$)).(?=.*[^@\n]\\.)","*")
    

    https://regex101.com/r/gpZZsL/2

    jshell上试用

    jshell> var s = "john.doe@example.en.com"
    s ==> "john.doe@example.en.com"
    
    jshell> s.replaceAll("(?<=.)[^@\n](?=[^@\n]*?[^@\n]@)|(?:(?<=@.)|(?!^)\\G(?=[^@\n]*$)).(?=.*[^@\n]\\.)","*")
    $9 ==> "j******e@e********n.com"
    
  3. # 3 楼答案

    正则表达式是一项要求吗¯(°_o)/¯

    你也可以这样做:

    int atIndex = email.indexOf("@");
    int lastDotIndex = email.lastIndexOf(".");
    
    String maskedEmail = IntStream.range(0, email.length())
            .boxed()
            .map(i -> i==0 || (i>=atIndex-1 && i<=atIndex+1) || i>=lastDotIndex ? 
                       email.charAt(i) : '*')
            .map(String::valueOf)
            .collect(Collectors.joining());