遮盖电子邮件ID的中心部分

huangapple go评论73阅读模式
英文:

Masking the centre part of the email ID

问题

我想按以下方式对电子邮件进行掩码处理:

输入                      |   输出
qwerty@gmail.com        : qw**ty@gmail.com
helloworld@gmail.com    : he******ld@gmail.com
stackoverflow@gmail.com : st*********ow@gmail.com
abcde@gmail.com         : ab*de@gmail.com
abcd@gmail.com          : a**d@gmail.com
abc@gmail.com           : a*c@gmail.com
ab@gmail.com            : a*@gmail.com
  1. 如果两端都有最多2个字符,最少显示每端的1个字符,或者仅掩码最后一个字符。

  2. 字符串长度至少为2个字符(ab@gmail.com)。

我查阅了一些提供的解决方案,但未能使用这些方案实现第二和第三种情况。是否有可能找到解决方法?我对正则表达式不太熟悉,所以不确定该如何继续。

参考链接:
https://stackoverflow.com/questions/33100298/masking-of-email-address-in-java

https://stackoverflow.com/questions/58361766/how-to-i-mask-all-string-characters-except-for-the-last-4-characters-in-java-usi

英文:

I want to mask the email id as follows :

Input                   |   Output
qwerty@gmail.com        : qw**ty@gmail.com
helloworld@gmail.com    : he******ld@gmail.com
stackoverflow@gmail.com : st*********ow@gmail.com
abcde@gmail.com         : ab*de@gmail.com
abcd@gmail.com          : a**d@gmail.com
abc@gmail.com           : a*c@gmail.com
ab@gmail.com            : a*@gmail.com
  1. Max 2 characters at both the extremes if available, minimum 1 character at each end are to be displayed or just mask the last character.

  2. The string has to be atleast 2 characters in length (ab@gmail.com).

I referred some of the solutions provided, but was not able to achieve the second and third scenario using those. Is there a possibility to find a fix ? I'm not well versed with regex, so I'm not sure which way to go ahead.

references :
https://stackoverflow.com/questions/33100298/masking-of-email-address-in-java

https://stackoverflow.com/questions/58361766/how-to-i-mask-all-string-characters-except-for-the-last-4-characters-in-java-usi

答案1

得分: 1

有关电子邮件地址中可以包含什么内容以及不能包含什么内容的有趣阅读材料,可以参考这个 Stack Overflow 帖子这个 Stack Overflow 帖子,特别是如果您想要使用正则表达式

以下是另一种完成任务的方法:

public static String maskEMailAddress(String emailAddy) {
    String id = emailAddy.substring(0, emailAddy.lastIndexOf("@"));
    String domain = emailAddy.substring(emailAddy.lastIndexOf("@"));
    if (id.length() <= 1) { 
        return emailAddy;
    }
    switch (id.length()) {
        case 2:
            id = id.substring(0,1) + "*";
            break;
        case 3:
            id = id.substring(0,1) + "*" + id.substring(2);
            break;
        case 4:
            id = id.substring(0,1) + "**" + id.substring(3);
            break;
        default:
            String masks = String.join("", java.util.Collections.nCopies(id.length() - 4, "*"));
            id = id.substring(0,2) + masks + id.substring(id.length() - 2);
            break;
    }

    String address = id + domain;
    return address;
}
英文:

Interesting reads regarding what can, and what can not be in an E-Mail Address would be this SO Post and this SO Post especially if you want to utilize Regular Expressions.

Here is another method to accomplish the task at hand:

public static String maskEMailAddress(String emailAddy) {
    String id = emailAddy.substring(0, emailAddy.lastIndexOf(&quot;@&quot;));
    String domain = emailAddy.substring(emailAddy.lastIndexOf(&quot;@&quot;));
    if (id.length() &lt;= 1) { 
        return emailAddy;
    }
    switch (id.length()) {
        case 2:
            id = id.substring(0,1) + &quot;*&quot;;
            break;
        case 3:
            id = id.substring(0,1) + &quot;*&quot; + id.substring(2);
            break;
        case 4:
            id = id.substring(0,1) + &quot;**&quot; + id.substring(3);
            break;
        default:
            String masks = String.join(&quot;&quot;, java.util.Collections.nCopies(id.length() - 4, &quot;*&quot;));
            id = id.substring(0,2) + masks + id.substring(id.length() - 2);
            break;
    }

    String address = id + domain;
    return address;
}

答案2

得分: 0

工作代码位于此处

考虑一个替换输入字符串中正则表达式的方法(感谢此答案):

String replace(String regex, String replacement, String input) {
    String result = "N/A";

    Matcher m = Pattern.compile(regex).matcher(input);
    if (m.find()) {
        int groupToReplace = 1;
        result = new StringBuilder(input).replace(m.start(groupToReplace),
                                                  m.end(groupToReplace),
                                                  replacement).toString();
    } else {
        throw new IllegalStateException("internal error");
    }

    return result;
}

然后,不同的情况可以隔离到客户端代码中。在这里,我们假设“电子邮件 ID”已从电子邮件地址中剥离出来。(例如,qwertyinput,而不是 qwerty@gmail.com)。代码片段:

// TODO: the regex strings can be compiled into proper Pattern objects
if (numChars == 2) {
    regex = ".(.)";
    replacement = ASTERISK;
} else if (numChars == 3) {
    regex = ".(.)";
    replacement = ASTERISK;
} else if (numChars == 4) {
    regex = ".(..).";
    replacement = ASTERISK + ASTERISK;
} else {
    regex = "..(.*)..";
    int numAsterisks = numChars - 4;

    // requires JDK 11+
    replacement = ASTERISK.repeat(numAsterisks);
}

String result = replace(regex, replacement, input);

请注意,上述代码中的String.repeat是在JDK 11中引入的。

虽然这并不高效或优雅,但在一定程度上是可读的(特别是如果经过充分的单元测试)。它对构成电子邮件地址的内容进行了简单处理。

另一种不使用正则表达式的解决方案在此处中。

英文:

Working code is located here

Consider a method that replaces a regex within an input string (credit to this answer):

String replace(String regex, String replacement, String input) {
    String result = &quot;N/A&quot;;

    Matcher m = Pattern.compile(regex).matcher(input);
    if (m.find()) {
        int groupToReplace = 1;
        result = new StringBuilder(input).replace(m.start(groupToReplace),
                                                  m.end(groupToReplace),
                                                  replacement).toString();
    } else {
        throw new IllegalStateException(&quot;internal error&quot;);
    }

    return result;
}

then the various cases can be isolated into client code. Here, we assume that the "email id" has been stripped from the email address. (e.g. qwerty is input and not qwerty@gmail.com). Code snippet:

// TODO: the regex strings can be compiled into proper Pattern objects
if (numChars == 2) {
    regex = &quot;.(.)&quot;;
    replacement = ASTERISK;
} else if (numChars == 3) {
    regex = &quot;.(.).&quot;;
    replacement = ASTERISK;
} else if (numChars == 4) {
    regex = &quot;.(..).&quot;;
    replacement = ASTERISK + ASTERISK;
} else {
    regex = &quot;..(.*)..&quot;;
    int numAsterisks = numChars - 4;

    // requires JDK 11+
    replacement = ASTERISK.repeat(numAsterisks);
}

String result = replace(regex, replacement, input);

Above, note that String.repeat was introduced in JDK 11.

This is neither efficient nor elegant but is somewhat readable (esp. if unit-tested thoroughly). It has a simplistic treatment of what constitutes an email address.

Another solution, which doesn't use regular expressions, is included here.

答案3

得分: 0

public static void main(String[] args) {
    String str = "qwerty@gmail.com\n"
            + "helloworld@gmail.com\n"
            + "stackoverflow@gmail.com\n"
            + "abcde@gmail.com\n"
            + "abcd@gmail.com\n"
            + "abc@gmail.com\n"
            + "ab@gmail.com";

    // 9 matcher group in total
    Pattern pattern = Pattern.compile("(?:(\\w{2})(\\w+)(\\w{2}@.*)|(\\w)(\\w{1,2})(\\w@.*)|(\\w)(\\w)(@.*))");
    List<Integer> groupIndex = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
    for (String email : str.split("\n")) {
        Matcher matcher = pattern.matcher(email);
        if(matcher.find()) {
            List<Integer> activeGroupIndex = groupIndex.stream()
                    .filter(i -> matcher.group(i) != null)
                    .collect(Collectors.toList());
            String prefix = matcher.group(activeGroupIndex.get(0));
            String middle = matcher.group(activeGroupIndex.get(1));
            String suffix = matcher.group(activeGroupIndex.get(2));
            System.out.printf("%s%s%s%n", prefix, "*".repeat(middle.length()), suffix);
        }
    }
}

Output:

qw**ty@gmail.com
he******ld@gmail.com
st*********ow@gmail.com
ab*de@gmail.com
a**d@gmail.com
a*c@gmail.com
a*@gmail.com

Note: "String repeat​(int count)" only works from Java 11 and up.

英文:

Alternative regex:

&quot;(?:(\\w{2})(\\w+)(\\w{2}@.*)|(\\w)(\\w{1,2})(\\w@.*)|(\\w)(\\w)(@.*))&quot;

Regex in context:

public static void main(String[] args) {
    String str = &quot;qwerty@gmail.com\n&quot;
            + &quot;helloworld@gmail.com\n&quot;
            + &quot;stackoverflow@gmail.com\n&quot;
            + &quot;abcde@gmail.com\n&quot;
            + &quot;abcd@gmail.com\n&quot;
            + &quot;abc@gmail.com\n&quot;
            + &quot;ab@gmail.com&quot;;

    // 9 matcher group in total
    Pattern pattern = Pattern.compile(&quot;(?:(\\w{2})(\\w+)(\\w{2}@.*)|(\\w)(\\w{1,2})(\\w@.*)|(\\w)(\\w)(@.*))&quot;);
    List&lt;Integer&gt; groupIndex = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
    for (String email : str.split(&quot;\n&quot;)) {
        Matcher matcher = pattern.matcher(email);
        if(matcher.find()) {
            List&lt;Integer&gt; activeGroupIndex = groupIndex.stream()
                    .filter(i -&gt; matcher.group(i) != null)
                    .collect(Collectors.toList());
            String prefix = matcher.group(activeGroupIndex.get(0));
            String middle = matcher.group(activeGroupIndex.get(1));
            String suffix = matcher.group(activeGroupIndex.get(2));
            System.out.printf(&quot;%s%s%s%n&quot;, prefix, &quot;*&quot;.repeat(middle.length()), suffix);
        }
    }
}

Output:

qw**ty@gmail.com
he******ld@gmail.com
st*********ow@gmail.com
ab*de@gmail.com
a**d@gmail.com
a*c@gmail.com
a*@gmail.com

Note: "String repeat​(int count)" only works from Java 11 and up.

huangapple
  • 本文由 发表于 2020年9月21日 23:18:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63995240.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定