[英]Regular expression for numbers and one decimal
我似乎無法使用簡單的正則表達式。 這是我目前所擁有的:
$(".Hours").on('input', function (e) {
var regex = /^\d+(\.\d{0,2})?$/g;
if (!regex.test(this.value)) {
if (!regex.test(this.value[0]))
this.value = this.value.substring(1, this.value.length);
else
this.value = this.value.substring(0, this.value.length - 1);
}
});
我需要用戶只能輸入數字和一位小數(小數點后只有兩個數字)。 它現在工作正常,除了用戶不能以小數開頭。
可接受:
23.53
0.43
1111.43
54335.34
235.23
.53 <--- Not working
不可接受:
0234.32 <--- The user can currently do this
23.453
1.343
.234.23
1.453.23
這有什么幫助嗎?
正則表達式 -
^(?:0|[1-9]\d+|)?(?:.?\d{0,2})?$
正則表達式 -
^(\d+)?([.]?\d{0,2})?$
說明
Assert position at the beginning of the string «^»
Match the regular expression below and capture its match into backreference number 1 «(\d+)?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regular expression below and capture its match into backreference number 2 «([.]?\d{0,2})?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match the character “.” «[.]?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d{0,2}»
Between zero and 2 times, as many times as possible, giving back as needed (greedy) «{0,2}»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
這是一個建議: /^((\\d|[1-9]\\d+)(\\.\\d{1,2})?|\\.\\d{1,2})$/
。
允許: 0
, 0.00
, 100
, 100.1
, 100.10
, .1
, .10
...
拒絕: 01
, 01.1
, 100.
, .100
, .
...
這是否滿足您的需求:
var regex = /^\d+([.]?\d{0,2})?$/g;
你的正則表達式: var regex = /^\\d+(\\.\\d{0,2})?$/g;
你需要什么: var regex = /^\\d*(\\.\\d{1,2})?$/;
您要求小數點前至少有一位數字 ( \\d+
)。 我也改變了它,所以如果你包含一個小數,它后面必須至少有一個數字。
這將迫使您在小數點分隔符后添加數字:
^\d+([.]\d)?$
示例:
如果你想要更多的數字; 3 為前; 確保將小數后的數字的 min 固定為“1”
^\d+([.]\d{1,3)?$
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.