简体   繁体   中英

Replace string not in given regex java

I try to replace string which not found in given regex.

Regex: (^.{1})|((.{1})(@.*))

Eg: If given input is dineshkani.n@gmail.com the above regex will extract "d", "n@gmail.com" . I try to replace characters other than this regex find. I tried to get d**********n@gmail.com

Is there any way to replace like this.

Thanks in advance.

Why don't you join those parts together? In Java using join method:

String email = String.join("*****",arrayOfSplits);

Can you replace characters that exist between two anchor points using a regular expression? Yes.

Take a look at the helpful resources below.

Start of String and End of String Anchors

SO Question about obfuscating emails with REGEX patterns

You are on the right path. Your pattern should contain at least 3 capture groups . The first capture group will be the first character in the string, email address in your example. The second capture group will be the characters from position 2 to the penultimate position before the @ symbol. And the third capture group will be the rest of the characters. Using your email as an example:

     [d]              [ineshkani.]       [n@gmail.com]
Capture group 1 --- Capture group 2 --- Capture group 3

Now that he groups are captured properly, we want to perform a replacement on capture group 2 that will replace each char with some obfuscation value, * for example. That will require a back reference to group 2.

([\w|\d]{1})  # This says match either a word or digit char occurring once
([\S]+)       # Match a non whitespace character with a greedy qualifier
(\S{1}\@\S+)  # Match a non whitespace character then an '@' then the rest of the characters until whitespace is found. 

Now you will need to use the backreference to group 2 in your Java replace function. See this SO answer for a good example of ways to perform regex replace on capture groups. You will need to use .replaceAll() and pass the capture group and the replacement string. I hope this helps you solve your problem and understand what is going on when you use regular expressions to replace strings in Java.

For more information on a greedy quantifier see the Regex Tutorial.

This is probably easier to not use regex at all.

Why not just use a StringBuilder and just look from 1 to lastIndexOf("@") - 1 and set the char as *

String email = "dineshkani.n@gmail.com";
StringBuilder sb = new StringBuilder(email);
int mp = sb.lastIndexOf("@");

for (int i = 1; i < mp - 1; i++) {
    sb.setCharAt(i, '*');
}

Output:

d**********n@gmail.com

Note : as mentioned in the comments, you'll have to check with this solution if the email is something like dn@gmail.com , it will just print that as is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM