用于逗号分隔数字的 JavaScript 验证的 RegEx
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7944065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RegEx for JavaScript validation of comma separated numbers
提问by pradeep kumar
I have one text box, it can have values like 1 or 1,2 or 1,225,345,21 ie multiple values. But now I want to validate this input.
我有一个文本框,它可以有像 1 或 1,2 或 1,225,345,21 这样的值,即多个值。但现在我想验证这个输入。
toString().match(/^(([0-9](,)?)*)+$/)
This is code I'm using. It is validating correct only, but one problem when user enter values like this:
这是我正在使用的代码。它仅验证正确,但是当用户输入这样的值时会出现一个问题:
inputval:1,22,34,25,645(true)
inputval:1,22,34,25,645,(falues)
When the user enters comma (,) as last it should throw an error.
当用户最后输入逗号 (,) 时,它应该抛出一个错误。
Can any one help me please?
任何人都可以帮助我吗?
回答by Ariel
Just manually include at least one:
只需手动包含至少一个:
/^[0-9]+(,[0-9]+)*$/
let regex = /[0-9]+(,[0-9]+)*/g
console.log('1231232,12323123,122323',regex.test('1231232,12323123,122323'));
console.log('1,22,34,25,645,',regex.test('1,22,34,25,645,'));
console.log('1',regex.test('1'));
回答by xanatos
Variants on the Ariel's Regex :-)
Ariel 正则表达式的变体 :-)
/^(([0-9]+)(,(?=[0-9]))?)+$/
The ,
must be followed by a digit (?=[0-9])
.
在,
后面必须跟一个数字(?=[0-9])
。
Or
或者
/^(([0-9]+)(,(?!$))?)+$/
The ,
must not be followed by the end of the string (?!$)
.
将,
不得其次是字符串的结尾(?!$)
。
/^(?!,)(,?[0-9]+)+$/
We check that the first character isn't a ,
(?!,)
and then we put the optional ,
before the digits. It's optional because the first block of digits doesn't need it.
我们检查第一个字符是否不是 a ,
(?!,)
,然后我们将可选,
字符放在数字之前。它是可选的,因为第一个数字块不需要它。