Regular slowdown

I cannot perform a regex replacement

for example, I have a letter

felipe@gmail.com

and I want to replace

f****e@g***l.com

I already have a start

(?<=.).(?=[^@]*?.@)|(?<=\@.).

Below are links where I am testing

REGEX

+4
source share
5 answers

With a little extra customization per template, you can achieve this:

"felipe@gmail.com".replaceAll("(?<=[^@])[^@](?=[^@]*?.[@.])", "*");

It will give you f****e@g***l.com.

Perhaps a more efficient and more readable solution can find the indices @and ., and combining the desired result from the substrings:

int atIndex = email.indexOf('@');
int dotIndex = email.indexOf('.');
if (atIndex > 2 && dotIndex > atIndex + 2) {
  String masked = email.charAt(0)
    + email.substring(1, atIndex - 1).replaceAll(".", "*")
    + email.substring(atIndex - 1, atIndex + 2)
    + email.substring(atIndex + 2, dotIndex - 1).replaceAll(".", "*")
    + email.substring(dotIndex - 1);
  System.out.println(masked);
}
+5
source

I found this: (?<=.)([^@])(?!@)(?=.*@)|(?<!@)([^@])(?!.*@)(?!\.)(?=.*\.)

Demo

+3
source

:

String str = "felipe@gmail.com";
String regex = "(.)(.*?)(.@.)(.*?)(.\\..*)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
String result = "";
if (matcher.find()) {
    result = matcher.group(1) + matcher.group(2).replaceAll(".", "*")
            + matcher.group(3) + matcher.group(4).replaceAll(".", "*")
            + matcher.group(5);
}

System.out.println(result);// output = f****e@g***l.com
+2

StringBuilder .

, @, .co.uk

, :

        String email = "felipe@gmail.com";
        StringBuilder sb = new StringBuilder(email);
        int mp = sb.lastIndexOf("@");
        int dp = sb.substring(mp).indexOf(".");
        for (int i = 1; i < sb.length(); i++) {
            if (i != mp && i != mp - 1 && i != mp + 1 && i != ((mp + dp) - 1) && i < (dp + mp)) {
                sb.setCharAt(i, '*');
            }
        }

Of course, there are situations when this will not work (i.e. @in the domain), and the code is a bit messy, but it can be useful at a certain stage.

Demo

+1
source

template:

^(.)[^@]*([^@])@(.).*(.)\.([a-z]+)$

Replacement:

\1***\2@\3***\4.\5

Limit: does not work with single-character user names and single-character domain names, for example. I@home.com or john@B.com.

+1
source

Source: https://habr.com/ru/post/1688284/


All Articles