Home > Mobile >  How to replace a part of email domain string in Java
How to replace a part of email domain string in Java

Time:06-22

I have an email for eg - [email protected] or [email protected] and I want to replace it with [email protected] for all the emails specifically If they have a prefix before ps.

So far I tried

final String string = "[email protected]";
final Pattern pattern = Pattern.compile("\\@[^.ps]*");
final Matcher matcher = pattern.matcher(string);    
final String result = matcher.replaceAll("");

But the final result is john.doe.ps.com and not [email protected]

CodePudding user response:

You can do this in a single replacement.

Search using this regex:

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

and replace with empty string.

RegEx Demo

Java Code:

final String string = "[email protected]";
result = string.replaceFirst("(?<=@)(?:[^\\n.] \\.)*(?=ps\\.)", "");
//=> [email protected]

RegEx Details:

  • (?<=@): Lookbehind to assert that we have @ before the current position
  • (?:[^.] \.)*: Match 1 of non-dot characters followed by a dot. Repeat this group 0 or more times. -(?=ps\.): Lookahead to assert that we have ps. ahead of the current position

CodePudding user response:

I made it work by adding @.

final String result = matcher.replaceAll("@");
  • Related