正则表达式允许最多10位数后跟一个逗号和3位数 [英] Regex to allow max 10 digits followed by only one comma and 3 more digits
问题描述
我正在使用正则表达式,只允许逗号前最多10位数字,逗号后最多3位数。
I am working on a regex for allowing only max 10 digits before comma and max 3 digits after comma.
到目前为止,我已经想出了这个:
So far i have come up with this:
^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$.
我将在javascript中验证输入。
I am going to validate input in javascript.
我正在使用sap.m.input控件,并且在实时更改事件中捕获用户的击键。
I am using sap.m.input control, and user's keystroke is captured on live change event.
以下示例被接受为用户输入:
Following examples are accepted as user input:
1234567890,123
4,1
234,45
56457
1234567890,123
4,1
234,45
56457
输入必须始终以自然数开头,并且只能出现逗号。
Input must always begin with a natural number and only comma should be appear.
使用上面提到的正则表达式,我能够避免第一个数字为零,但它不考虑此输入值 - 1,23
。
Using the above mentioned regex, i am able to avoid first digit as zero but it is not considering this input value - 1,23
.
我在应用程序中添加了以下代码:
I have added the following code in the application:
var input = oEvent.getSource().getValue();
var isValid = false;
var regex = /^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$/;
isValid = regex.test(input);
if (isValid == false) {
// oEvent.getSource().setValueState("Error");
input = input.replace(/[^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})]/g,"");
oEvent.getSource().setValue(input);
return;
}
我还想避免输入字段中的空白条目和空格。我想在实时更改事件中用空格替换不需要的字符。截至目前,我无法使用上述代码替换其他字符。
I also want to avoid blank entry and space in the input field. I want replace unwanted characters with space on live change event. As of now, i am unable to replace other characters using the above mentioned code.
请建议如何形成完美的正则表达式来处理这种情况。
Please suggest ways to form perfect regex to handle this scenario.
谢谢。
推荐答案
^[1-9]\d{0,9}(,\d{0,3})?$
-
[1-9]
- 第一个号码必须是1-9 -
\d {0,9}
- 在第一个号码后,可以有0-9个数字 -
,\\\ { 0,3}
- 逗号后3位数字 -
()?
- 逗号部分是可选的 [1-9]
- first number must be 1-9\d{0,9}
- after first number, there can be 0 - 9 digits,\d{0,3}
- 3 more digits after comma()?
- the comma part is optional
在线试用: https://regex101.com/r/YsaXvo/1
这篇关于正则表达式允许最多10位数后跟一个逗号和3位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!