开发者

C# - Regexp - ArgumentException

开发者 https://www.devze.com 2022-12-14 03:15 出处:网络
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\");

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\Document开发者_Python百科s\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.


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");


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

Try escaping these directly: \[ and \].


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})\\]");


\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})\]")


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

example:

int total = Regex.Matches(data, Regex.Escape(newTag)).Count;
0

精彩评论

暂无评论...
验证码 换一张
取 消