views:

243

answers:

4

Hello, 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.

A: 

The \x5B and \x5D are converted to [ and ] respectively, making this an invalid RegEx.

Try escaping these directly: \[ and \].

Oded
No thats not the resolution.Regex r = new Regex("Mond ([1-9]) \[([1-9]):([1-9][0-9]{0,2}):([1-9][0-9]{0,2})\]");the error is:unknown escapesequence
Marcel Altmann
+2  A: 

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");
Amarghosh
thanks for the resolution
Marcel Altmann
A: 

You need to double the \ character.

   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 this would be equivalent to

        Regex r = new Regex("Mond ([1-9]) \\[([1-9]):([1-9][0-9]{0,2}):([1-9][0-9]{0,2})\\]");
Gregory Pakosz
A: 

\x5Bis [ and \x5D is ]. As you should know those characters already have a meaning in RegEx, so you should escape them by putting a \ in front of it. I'd use a verbatim string so you don't have to use \ to get a \:

new Regex(@"Mond ([1-9]) \[([1-9]):([1-9][0-9]{0,2}):([1-9][0-9]{0,2})\]")
helium