I have an email "xyz@gmail@.com", 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@gmail@.com", @"^([^,]*@[^,]*)@(.*)$", "")
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.
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 .
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.