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.