Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

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

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.

      parsing "^([0][1-9]|1[0-2])[/-.]" - [x-y] range in reverse order. 
      Description: An unhandled exception occurred during the execution of the current web request.          
      Please review the stack trace for more information about the error and where it originated in  
      the code. 

      Exception Details: System.ArgumentException: parsing "^([0][1-9]|1[0-2])[/-.]" - [x-y] range 
      in reverse order.

After messing around for a bit and trying to find error in my regex I simply changed me regex to

  ([0][1-9]|1[0-2])[-/.]  so basically only changed this [/-.] to [-/.]

and it worked.

Then I tried some other combinations which worked.

   [/-]  [/.]  [/.-]  [/-?]

Then I tried some others which didn't work.

   [/-*]  [/-+]

So apparently "-" has problem at some places but no problem at others. Is that a bug? or am I missing something?

Update

Thanks guys for pointing out that "-" is assumed as range if it is in middle or not escaped by "".

However, why did it work for [/-?] or [/-?], is it really defining range here or taking it literally?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not a bug. Inside a character class (denoted by […]) the - character must be first (some flavours allow first or last, I believe) if it is to be included as a literal. Otherwise it is expected to denote a range, such as 0-9 or A-Z or even /-..

The problem is that according to Unicode, the . comes before the /, so the range is interpreted to be backward, equivalent to specifying a range 7-4.

If you used [.-/], I would not expect a parse exception, but you wouldn't get the results you expected.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...