2

小数点記号を使用して数値正規表現を作成する方法と、長さを制限する方法

私はこれを作成します:

^[0-9]([0-9]*[.]?[0-9]){1,10}$

次に、1234567890.1234567890 は有効ですが、20 (+1 -> 小数点記号) 文字を使用しています。

10文字に制限するにはどうすればよいですか?

有効:

1234567890
123456789.0
12345678.90
1234567.890
123456.7890
12345.67890
12345.67890
1234.567890
123.4567890
12.34567890
1.234567890

有効ではありません:

12345678901
12345678901.
123456789.01
12345678.901
1234567.8901
123456.78901
12345.678901
12345.678901
1234.5678901
123.45678901
12.345678901
1.2345678901
.12345678901

前もって感謝します

4

2 に答える 2

4
^(?:\d{1,10}|(?!.{12})\d+\.\d+)$

説明:

^          # Start of string
(?:        # Either match...
 \d{1,10}  # an integer (up to 10 digits)
|          # or
 (?!.{12}) # (as long as the length is not 12 characters or more)
 \d+\.\d+  # a floating point number
)          # End of alternation
$          # End of string

.123(あなたの例のように)または123.は無効であることに注意してください。

于 2013-02-20T22:22:33.650 に答える
1

正規表現を使用して長さをカウントしないと、より明確になり、おそらくさらに高速になります。に対してテストし^\d+(?:\.\d+)$、ドットを削除して長さを取得します。

本当に 1 つの正規表現にする必要がある場合は、先読みを使用して形式長さを個別に確認できます。

^\d{1,10}$|^(?=.{11}$)\d+\.\d+$

説明:

^          # At the start of the string
(?:        # either
 \d{1,10}  # up to 10 digits
|          # or
 (?=       # from here
  .{11}    # 11 characters
  $        # to the end
 )         # and as well
 \d+\.\d+  # two dot-separated digit sequences
)          # 
$          # 
于 2013-02-20T22:27:07.753 に答える