2

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.

5 Answers5

3

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
  • 58,710
  • 11
  • 92
  • 121
1

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

Try escaping these directly: \[ and \].

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 1
    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 –  Dec 10 '09 at 09:29
0

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
  • 69,011
  • 20
  • 139
  • 164
0

\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
  • 1,077
  • 1
  • 9
  • 15
0

When you see this error, use Regex.Escape(string) that will solve the error.

example:

int total = Regex.Matches(data, Regex.Escape(newTag)).Count;
niek tuytel
  • 899
  • 7
  • 18