How to replace a part of email domain string in Java

Viewed 50

I have an email for eg - john.doe@ny.ps.com or john.doe@ma.ps.com and I want to replace it with john.doe@ps.com for all the emails specifically If they have a prefix before ps.

So far I tried

final String string = "john.doe@ny.ps.com";
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 john.doe@ps.com

2 Answers

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 = "john.doe@ny.ps.com";
result = string.replaceFirst("(?<=@)(?:[^\\n.]+\\.)*(?=ps\\.)", "");
//=> john.doe@ps.com

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

I made it work by adding @.

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