正規表現でテキストボックスを検証しようとしています...
regex expression=(\d{0,4})?([\.]{1})?(\d{0,2})
小数点に問題があります。小数点はオプションです。正規表現は小数点以下1桁のみを検証する必要があります。
example 1.00 ,23.22 , .65 is valid
1.. or 23.. is invalid.
正規表現を改善するための提案はありますか?
正規表現でテキストボックスを検証しようとしています...
regex expression=(\d{0,4})?([\.]{1})?(\d{0,2})
小数点に問題があります。小数点はオプションです。正規表現は小数点以下1桁のみを検証する必要があります。
example 1.00 ,23.22 , .65 is valid
1.. or 23.. is invalid.
正規表現を改善するための提案はありますか?
これを試してください:^\d{1,4}(\.\d{1,2})?$
一致する必要があります:
1
200
9999
12.35
522.4
だがしかし :
1000000
65.
.65
10.326
65..12
編集 :
65または9999に一致させたい場合は、代わりにこれを使用してください(コメントを参照):
^\d{1,4}(\.(\d{1,2})?)?$
このための正規表現を作成することは確かに可能ですが、データ型またはクラスをチェックするか、入力の小数をスキャンしてからカウントする方が簡単なようです。たとえば、Rubyを使用します。
値が浮動小数点数または整数であることを確認してください。
# Literal value is a float, so it belongs to the Float class.
value = 1.00
value.class == Fixnum or value.class == Float
=> true
# Literal value is an integer, so it belongs to the Fixnum class.
value = 23
value.class == Fixnum or value.class == Float
=> true
小数を数え、1つしかないことを確認します。
# Literal value is a float. When cast as a string and scanned,
# only one decimal should be found.
value = 23.22
value.to_s.scan(/\./).count <= 1
=> true
# The only way this could be an invalid integer or float is if it's a string.
# If you're accepting strings in the first place, just cast all input as a
# string and count the decimals it contains.
value = '1.2.3'
value.to_s.scan(/\./).count <= 1
=> false