简体   繁体   中英

C# Removing all extra occurrences BEYOND the FIRST in string

So, I have some code that works the way I want it to, but I am wondering if there is a better way to do this with a regex? I have played with a few regex but with no luck(And I know I need to get better with regex stuff).

This code is purely designed to remove any extra spaces or non email valid characters. Then it goes through and removes extra @ symbols beyond the first.

        List<string> second_pass = new List<string>();
        string final_pass = "";

        if (email_input.Text.Length > 0)
        {
            string first_pass = Regex.Replace(email_input.Text, @"[^\w\.@-]", "");

            if (first_pass.Contains("@"))
            {
                second_pass = first_pass.Split('@').Select(sValue => sValue.Trim()).ToList();

                string third_pass = second_pass[0] + "@" + second_pass[1];

                second_pass.Remove(second_pass[0]);
                second_pass.Remove(second_pass[1]);

                if (second_pass.Count > 0)
                {
                    final_pass = third_pass + string.Join("", second_pass.ToArray());
                }
            }

            email_output.Text = final_pass;
        }

Going by your description and not the code:

var final_pass = email_input.Text;
var atPos = final_pass.IndexOf('@');
if (atPos++ >= 0)
    final_pass = final+pass.Substring(0, atPos) + Regex.Replace(final_pass.Substring(atPos), "[@ ]", "");

For an (almost) pure regex solution, using a state cheap, this seems to be working:

var first = 0;
final_pass = Regex.Replace(final_pass, "(^.+?@)?([^ @]+?)?[@ ]", m => (first++ == 0) ? m.Groups[1].Value+m.Groups[2].Value : m.Groups[2].Value);

If you can get by by replacing only the captured groups, then this should be able to work.

([^\\w\\.\\@\\-])|(?<=\\@).*?(\\@)

Demo

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM