.NET Regex Error: [x-y] range in reverse order

后端 未结 3 877
死守一世寂寞
死守一世寂寞 2020-12-06 04:05

I am creating a Regex and so far I did this and tried it,

 ^([0][1-9]|1[0-2])[/-.]

and I get the following error.

      p         


        
3条回答
  •  孤街浪徒
    2020-12-06 04:37

    The problem is with this part:

    [/-.]
    

    That means "the range of characters from '/' to '.'" - but '/' comes after '.' in Unicode, so the range makes no sense.

    If you wanted it to mean "slash, dash or period" then you want:

    [/\-.]
    

    ... in other words, you need to escape the dash. Note that if this is in a regular C# string literal, you'll need to perform another level of escaping too:

    string pattern = "[/\\-.]";
    

    Using a verbatim string literal means you don't need to escape the backslash:

    string pattern = @"[/\-.]";
    

    Alternatively, as Jay suggested, you can just put the dash at the start:

    [-/.]
    

    or end:

    [/.-]
    

    (I've just tested, and all three of these options work.)

提交回复
热议问题