Int32的正则表达式

时间:2012-08-28 07:21:28

标签: sql-server regex

我试图为Int32号写一个正则表达式。我想写一个匹配-2,147,483,648和2,147,483,647之间的任何数字的正则表达式,但我不知道如何写一个从负值到正值的表达式。

有什么想法吗?

4 个答案:

答案 0 :(得分:4)

为什么不只使用Int32.Parse(value),如果OverflowException表示小于MinValue或大于MaxValue的数字,则可以捕获value

答案 1 :(得分:1)

要在指定范围内获得负值和正值 ,您可以执行以下操作:

编辑:数字可以从0开始(更正),数字范围从-2147483648到2147483647不是-2147483647到2147483648(已更正)

^(
-?\d{1,9}|
-?1\d{9}|
-?20\d{8}|
-?21[0-3]\d{7}|
-?214[0-6]\d{6}|
-?2147[0-3]\d{5}|
-?21474[0-7]\d{4}|
-?214748[012]\d{4}|
-?2147483[0-5]\d{3}|
-?21474836[0-3]\d{2}|
214748364[0-7]|
-214748364[0-8]
)$

逐行评论:

^(                  //start of line, or it will match part of the number and not the whole one
-?\d{1,9}|          //get any number with 9 digits
-?1\d{9}|           //get any number with 10 digits starting with 1
-?20\d{8}|          //get any number with 10 digits starting with 20
-?21[0-3]\d{7}|     //get any number with 10 digits starting with 21
                    //         (and the third digit in the range 0-3)
-?214[0-6]\d{6}|    //I think from now on it is understood
-?2147[0-3]\d{5}|
-?21474[0-7]\d{4}|
-?214748[012]\d{4}|
-?2147483[0-5]\d{3}|
-?21474836[0-3]\d{2}|
214748364[0-7]|     //max corner case
-214748364[0-8]     //min corner case
)$

答案 2 :(得分:0)

您可以使用asp:CompareValidator

执行相同的操作
<asp:TextBox ID="txtNumber" runat="server" /> 
<asp:CompareValidator ID="validator" runat="server" ControlToValidate="txtNumber" Operator="DataTypeCheck" Type="Double" ErrorMessage="Please enter only numeric values" /

答案 3 :(得分:0)

这真是一个丑陋的正则表达式:

使用千位分隔符(逗号):1,234,567

<强> In action

^
  (
   -?
    (
     1(,\d\d\d){0,3}
    |2(,\d\d\d){0,2}
    |2,(0\d\d,\d\d\d,\d\d\d
       |1[0-3]\d,\d\d\d,\d\d\d
       |14[0-6],\d\d\d,\d\d\d
       |147,[0-3]\d\d,\d\d\d
       |147,4[0-7]\d,\d\d\d
       |147,48[0-2],\d\d\d
       |147,483,[0-5]\d\d
       |147,483,6[0-3]\d
       |147,483,64[0-7])
    |[1-9]\d{0,2}(,\d\d\d){0,2}
    )
  |0
  |-2,147,483,648
)$

没有千位分隔符:1234567

<强> In action

^
  (
   -?
    (
     1\d{0,9}
    |2(0\d{8}
      |1[0-3]\d{7}
      |14[0-6]\d{6}
      |147[0-3]\d{5}
      |1474[0-7]\d{4}
      |14748[0-2]\d{3}
      |147483[0-5]\d{2}
      |1474836[0-3]\d
      |14748364[0-7])
    |[1-9]\d{0,8}
    )
  |0
  |-2147483648
)$