2

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

有任何想法吗 ?

4

4 回答 4

4

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

编辑:数字可以从 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
)$
于 2012-08-28T07:28:15.973 回答
3

为什么不直接使用Int32.Parse(value),您可以捕获OverflowException是否value表示小于 MinValue 或大于 MaxValue 的数字。

于 2012-08-28T07:27:23.413 回答
0

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

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

在行动

^
  (
   -?
    (
     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

在行动

^
  (
   -?
    (
     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
)$
于 2012-08-29T23:54:22.060 回答
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" /
于 2012-08-28T07:28:58.663 回答