Reputation: 45
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
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 rightIn Java
str.replaceAll("(?:\\.|\\+[^@]*)(?=.*@)","")
Upvotes: 1
Reputation: 10466
You can try with that:
\+[^@]*
Explanation:
\+
matches + where \ is the escape character[^@]*
matches anything until it reaches @, where * means zero or moreThe 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("");
Upvotes: 5