Reputation: 69
So, I'm trying to remove certain characters [.&@] before the final occurance of an @, but after that final @, those characters should be allowed.
This is what I have so far.
string pattern = @"\.|\&|\@(?![^@]+$)|[^a-zA-Z@]";
string input = "username@middle&[email protected]";
// input, pattern, replacement
string result = Regex.Replace(input, pattern, string.Empty);
Console.WriteLine(result);
Output: usernamemiddlesomethingelse@companycom
This currently removes all occurances of the specified characters, apart from the final @. I'm not sure how to get this to work, help please?
Upvotes: 1
Views: 41
Reputation: 2284
Just a simple solution (and alternative to complex regex) using Substring
and LastIndexOf
:
string pattern = @"[.@&]";
string input = "username@middle&[email protected]";
string inputBeforeLastAt = input.Substring(0, input.LastIndexOf('@'));
// input, pattern, replacement
string result = Regex.Replace(inputBeforeLastAt, pattern, string.Empty) + input.Substring(input.LastIndexOf('@'));
Console.WriteLine(result);
Try it with this fiddle.
Upvotes: 0
Reputation: 626804
You may use
[.&@]+(?=.*@)
Or, equivalent [.&@]+(?![^@]*$)
. See the regex demo.
Details
[.&@]+
- 1 or more .
, &
or @
chars(?=.*@)
- followed with any 0+ chars (other than LF) as many as possible and then a @
.See the C# demo:
string pattern = @"[.&@]+(?=.*@)";
string input = "username@middle&[email protected]";
string result = Regex.Replace(input, pattern, string.Empty);
Console.WriteLine(result);
// => [email protected]
Upvotes: 2