Manish
Manish

Reputation: 45

How to replace a part of email address using regex?

I want to replace a part of email address using regex. How to do it ?

For example : An email address [email protected] is there and I want to replace the part of that email address from + to before @ with '' so that final string will be [email protected].

I tried with this given below :

str.replaceAll("[^+[a-z]]","");

Upvotes: 3

Views: 817

Answers (2)

The fourth bird
The fourth bird

Reputation: 163277

If you want to match either a dot or a plus sign till an @, you could use a positive lookahead to assert an @ on the right for both cases and list each option using an alternation.

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

Explanation

  • (?: Non capture group
    • \. Match a dot
    • | Or
    • \+[^@]* Match + and 0+ times any char except a dot
  • ) Close group
  • (?=.*@) Positive lookahead, assert an @ to the right

Regex demo | Java demo

In Java

str.replaceAll("(?:\\.|\\+[^@]*)(?=.*@)","")

Upvotes: 1

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

You can try with that:

\+[^@]*

Explanation:

  1. \+ matches + where \ is the escape character
  2. [^@]* matches anything until it reaches @, where * means zero or more

The code is given below:

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

Regex Test Case

Upvotes: 5

Related Questions