简体   繁体   English

JavaScript正则表达式,用于带一个点和两个小数的正数

[英]JavaScript Regex for positive numbers with one dot and 2 decimal

I am quite new to regex and I have a problem with regex expression. 我对regex很陌生,我对regex表达式有疑问。

I want to only allow a user to enter positive numbers, with or without one dot and up to 2 decimals (can be only 1 decimal also). 我只允许用户输入带或不带一个点且最多2个小数(也只能是1个小数)的正数。 Upon user typing the text inside the textbox, and if they type the wrong format, I want to remove the other characters and replace the value with the correct format. 当用户在文本框中输入文本时,如果他们输入了错误的格式,我想删除其他字符并将值替换为正确的格式。

Valid examples: 有效的例子:

123.12
2
56754
92929292929292.12
0.21
3.1
.90

Invalid examples: 无效的示例:

12.1232
2.23332
e666.76
-1.23
-54.3242
3.98A
56B
BBB.12C
14.23.56
1..45

Currently I found one solution using the following regex : 目前,我发现使用以下正则表达式的一种解决方案:

$("#SomeElement").keyup(function () {
   this.value = this.value.replace(/(\.\d\d)\d+|([\d.]*)[^\d.]/, '$1$2')
});

There are two problems with that 有两个问题

  1. It allows me to enter multiple dots. 它允许我输入多个点。 (eg 123.89.80) (例如123.89.80)
  2. Even though if I type like letter "a" once, it filters but if I hold down the letter "a" in keyboard, it still allows to enter (eg AAAAAAAAA12), maybe is it because of "keyup" event? 即使我一次输入像字母“ a”一样,它也会过滤,但是如果我在键盘上按住字母“ a”,它仍然允许输入(例如AAAAAAAAA12),也许是因为“ keyup”事件?

Thank you in advance. 先感谢您。

I've tested this now and it works, give it a go: 我现在已经对此进行了测试,并且可以运行,试试吧:

$("#SomeElement").keyup(function () {
    this.value = this.value.replace(/([^\d]*)(\d*(\.\d{0,2})?)(.*)/, '$2');
});

I would not try to do this with one regex. 我不会尝试使用一个正则表达式来做到这一点。 Such regexes are sure to give you nightmares and lead to untold numbers of bugs. 此类正则表达式肯定会给您带来噩梦,并导致大量错误。 Save yourself the trouble, especially if you're new to regex. 为自己省去麻烦,特别是如果您不熟悉正则表达式。

I would break this task up into the following algorithm: 我将此任务分解为以下算法:

  1. Remove all the bad characters -- everything that isn't a digit or period. 删除所有不良字符-不是数字或句点的所有字符。

  2. Find the integral part of the number (all digits before the first period). 查找数字的整数部分(第一个句点之前的所有数字)。

  3. Find the fractional part of the number (all digits after the first period). 查找数字的小数部分(第一个句点之后的所有数字)。

  4. Put the pieces together, only adding the fractional part if there was a period in the input. 将各个部分放在一起,如果输入中有句点,则仅添加小数部分。

Let's put that in code: 让我们将其放在代码中:

$("#SomeElement").on('input', function () {
    var filtered = this.value.replace(/[^0-9.]/g, '').split('.')
    var integer = filtered.shift()
    var hasDecimal = filtered.length > 0
    var fraction = filtered.join('').slice(0, 2)
    this.value = integer + (hasDecimal ? '.' + fraction : '')
});

Oh, and bind to the input event, not keyup , keypress , or keydown . 哦,绑定到input事件,而不是keyupkeypresskeydown They all have downsides. 他们都有缺点。 And I might suggest saving the user's caret position using this.selectionStart and this.setSelectionRange() , or they're in for some choppy behavior if they try going back to edit part of their input. 而且我可能建议使用this.selectionStartthis.setSelectionRange()保存用户的插入符位置,或者如果他们尝试返回以编辑其部分输入,则他们可能会出现一些this.setSelectionRange()行为。 So that would look basically like: 所以基本上看起来像:

var caretPos = this.selectionStart
this.value = ...
this.setSelectionRange(caretPos, caretPos)

Though you might want to modify it a bit to get the behavior you need. 尽管您可能需要对其进行一些修改才能获得所需的行为。 Here's all that together in a JSFiddle . 这就是JSFiddle中的所有内容 Cheers. 干杯。

Try using the following regex : 尝试使用以下正则表达式

^\.?(?!-)\d+(?:\.\d{1,2})?$

see regex demo / explanation 参见正则表达式演示/说明

试试这个^\\s*(?=.*[1-9])\\d*(?:\\.\\d{1,2})?\\s*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM