0

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.
Community
  • 1
  • 1
ccsv
  • 8,188
  • 12
  • 53
  • 97

1 Answers1

1
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.

hometoast
  • 11,522
  • 5
  • 41
  • 58
  • I got an argument error was unhandled. I am guessing this is because the regex found nothing and there was no continue? – ccsv Jul 06 '15 at 18:20