azhar rahi
azhar rahi

Reputation: 337

Regex to replace multiple occurence of @ except first

I have an email "xyz@[email protected]", which contains two @ characters. What I want is to keep the first @ character and remove all the remaining 2 characters (even if there are more than two @ characters in email).

What I had tried to do is:

Regex.Replace("xyz@[email protected]", @"^([^,]*@[^,]*)@(.*)$", "")

but it is returning empty string. I am not sure how to replace the 2nd character, even I am not sure if I have correctly chosen the regex pattern.

Upvotes: 1

Views: 603

Answers (2)

Mike Jerred
Mike Jerred

Reputation: 10525

Regex will only match one occurrence, you can do this without regex though:

var parts = text.Split("@");
var result = parts[0] + "@" + string.Join("", parts.Skip(1));

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You may use

var result = Regex.Replace(text, @"(?<!^[^@]*)@", "");

See the regex demo. Details:

  • (?<!^[^@]*) - a negative lookbehind that makes sure there is no @ before the current location up to the string start
  • @ - a @ in other contexts.

In case you do not really have to use a regex,

var result = text.Substring(0, text.IndexOf("@")+1) + text.Substring(text.IndexOf("@")+1).Replace("@", "");

should also work. See the C# demo.

Upvotes: 3

Related Questions