regex works in online regex tester but not in .NET

后端 未结 1 1407
猫巷女王i
猫巷女王i 2021-01-28 11:04

the following demo works just fine online but not when I attempt to run it in c#/.NET

 var regex = new RegularExpressionAttribute(@\"@(?!.*?\\.\\.)[^@]+$\");
 As         


        
相关标签:
1条回答
  • 2021-01-28 11:44

    The RegularExpressionAttribute requires a full match of the string.

    In your case, you are only matching starting at the @ character, so you start somewhere in between of your string. This is just not good enough for the RegularExpressionAttribute. You can think of it adding an implicit ^ at the start to your expression (and an implicit $ at the end too, so you can drop that as well).

    So to fix this, you need to make sure that it has something to match at the start to, e.g. a .*?:

    new RegularExpressionAttribute(@".*?@(?!.*?\.\.)[^@]+");
    

    And then it works. You don’t need any other regular expression flags.


    Unfortunately, this behavior of RegularExpressionAttribute is mentioned nowhere in the documentation. You can verify it in the reference source however:

    // We are looking for an exact match, not just a search hit. This matches what
    // the RegularExpressionValidator control does
    return (m.Success && m.Index == 0 && m.Length == stringValue.Length);
    

    So it’s technically not an added ^ and $ but after finding a match, the start and end index are required to match the string’s start and end index (which is essentially the same thing).

    And if you think about it, this behavior makes a lot of sense for validation. After all, you want to make sure that a string matches a certain full-specified format, and not just check if some substring is valid.

    0 讨论(0)
提交回复
热议问题