简体   繁体   中英

iterating over a dictionary of Regex in C#

I have a function that finds and replaces a regex for an input string text

    public static string Replacements(string text)
    {

        string output = Regex.Replace(text, @"\b[a-zA-Z0-9.-_]+@[a-z][A-Z0-9.-]+\.[a-zA-Z0-9.-]+\b","email");

        return output;
    }

Lets say I want to put the replacement regex into a dictionary

    static Dictionary<string, string> dict1 = new Dictionary<string, string>
    {
        {@"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$", "phoneno"},
        {@"\b[a-zA-Z0-9.-_]+@[a-z][A-Z0-9.-]+\.[a-zA-Z0-9.-]+\b","email"},

    };

and I wanted to iterate over the dictionary to replace text. How would I do this? I tried the solution with the forloop here: What is the best way to iterate over a Dictionary in C#?

    public static string Replacements(string text)
    {

        string output = text;
        foreach (KeyValuePair<string, string> item in dict1)
        {
            output = Regex.Replace(text, item.Key, item.Value);
        }


        return output;
    }

But it did not work. Is there a better way to do this? I got an Argument exception was unhandled error:

parsing "^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$" - Quantifier {x,y} following nothing.
public static string Replacements(string text)
{

    string output = text;
    foreach (KeyValuePair<string, string> item in dict1)
    {
        //here replace output again
        output = Regex.Replace(output, item.Key, item.Value); 

    }


    return output;
}

If you want to apply many replacements, then you'll need to replace the result of the previous operation.

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