mouldycurryness
mouldycurryness

Reputation: 69

Regex - Removing specific characters before the final occurance of @

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

Answers (2)

Mikael Dúi Bolinder
Mikael Dúi Bolinder

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

Wiktor Stribiżew
Wiktor Stribiżew

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

Related Questions