Search code examples
c#regexargumentexception

C# - Regexp - ArgumentException


i want to match coordinates from a Browsergame. My Regex is:

        try
        {
            Regex r = new Regex("Mond ([1-9]) \x5B([1-9]):([1-9][0-9]{0,2}):([1-9][0-9]{0,2})\x5D");
            Match m = r.Match("Mond 1 [1:1:1]");
        }
        catch (ArgumentException ex)
        {
            Console.WriteLine(ex);
        }

And the error is:

System.ArgumentException: "Mond ([1-9]) [([1-9]):([1-9][0-9]{0,2}):([1-9][0-9]{0,2})]" wird analysiert - Zu viele )-Zeichen. bei System.Text.RegularExpressions.RegexParser.ScanRegex() bei System.Text.RegularExpressions.RegexParser.Parse(String re, RegexOptions op) bei System.Text.RegularExpressions.Regex..ctor(String pattern, RegexOptions options, Boolean useCache) bei WindowsFormsApplication7.Form2.comboBox1_SelectedIndexChanged(Object sender, EventArgs e) in C:\Users\Heavyfan\Documents\Visual Studio 2008\Projects\WindowsFormsApplication7\WindowsFormsApplication7\Form2.cs:Zeile 27. Eine Ausnahme (erste Chance) des Typs "System.ArgumentException" ist in System.dll aufgetreten.

What is the problem on my regex?

Sorry for my bad english. Thx for resolutions.


Solution

  • I didn't understand the error message, but it seems like an escaping problem - you haven't escaped your backslashes. Change the regex to one of the following:

    //verbatim 
    Regex r = new Regex(@"Mond ([1-9]) \x5B([1-9]):([1-9][0-9]{0,2}):([1-9][0-9]{0,2})\x5D");
    
    //or escaped
    Regex r = new Regex("Mond ([1-9]) \\x5B([1-9]):([1-9][0-9]{0,2}):([1-9][0-9]{0,2})\\x5D");