简体   繁体   中英

Is this a bug in dotnet Regex-Parser?

I just wrote a regexp to do a basic syntax checking if a string is a valid math formular. I just define a group of valid chars and check if a string matches (I shortend the regex a little:

    private static readonly String validFormuar =  @"^[\d\+-\*\/]+$";
    private static bool IsValidFormular(String value)
    {
        return Regex.IsMatch(value, validFormuar);
    }

I will only allow digits, +, -, * and / in this example.
Because +,* and / are special chars in regular expressions I escaped them.
However this code throws an ArgumentException (translated from german)

"^[\d\+-\*\/]+$" is beeing analyzed - [x-y]-area in reversed Order.

If I double escape the *

    private static readonly String validFormuar =  @"^[\d\+-\\*\/]+$";

the result is as expected.
Is this a bug in the System.Text.RegularExpressions parser? Because I consider my first regexp as correct. If not, why do I have to escape the "*" twice?

I think you'll find "-" is a special character in regexes as well (at least within the "[]" bits). It specifies a range of characters, as in "[0-9]" meaning and of "0123456789" .

The reason your second one works but your first doesn't is because:

  • + comes after * (error in range).
  • + comes before \\ (no error in range).

To clarify, your second regex (@"^[\\d\\+-\\\\*\\/]+$") actually means:

  • "\\d" ; or
  • "\\+" thru "\\\\" (quite a large range, including digits and uppercase letters) ; or
  • "*" ; or
  • "\\/"

Although it compiles, it's not what you want (because of that second bullet point). I'd try this instead:

@"^[\d\+\-\*\/]+$"

With @"" strings, you don't have to double-escape. In your sample, you also forgot to escape the "-". So the correct one would be:

@"^[\d\+\-\*\/]+$"

On the other hand, when inside [], you don't need to escape those (only "-"):

@"^[\d+\-*/]+$"

Include the - as first char in your expression. Otherwise the parser is looking for a range.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM