我试图得到一个正则表达式来检查数字和逗号,例如
这将通过
1
0,3,4
1,3
1,3,15,12
这不会经历
abc
1,,3,,4
1,3,
,1,1
我现在的正则表达式是
/[0-9]*[,][0-9]*/
它似乎不像我想要的那样工作我能得到一些帮助谢谢
使用此正则表达式^([0-9]+,)*[0-9]+$
var re = new RegExp('^([0-9]+,)*[0-9]+$');
function check(){
var str=$('#hi').val();
console.log(str);
if(str.match(re))
$('#result').html("Correct");
else
$('#result').html("InCorrect");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="hi">
<button onclick="check()">Check</button>
<p id="result"></p>
正则表达式:^\d+(?:,\d+)*$
var array = ['1', '0,3,4', 'abc', '1,,3,,4', '1,3,', ',1,1'];
for (var i of array) {
console.log(i + ' => ' + /^\d+(?:,\d+)*$/g.test(i))
}
这不是正则表达式,但这是一种方法:
// Your test input values (which I will assume are strings for this code):
/*
* 1
* 0,3,4
* 1,3
* 1,3,15,12
*/
const str = '1,3,15,12';
const isValid = str.split(',')
.map((val) => !isNaN(parseInt(val)))
.reduce((currentVal, nextVal) => currentVal && nextVal, true);
console.log(isValid);
你现在的正则表达式:/[0-9]*[,][0-9]*/
会匹配,
1,1
,6
4953,5433
5930,
等等
假设你想匹配逗号分隔的数字列表(每个数字都有任意数字),你需要:/\d+(,\d+)*/
其中\d
是[0-9]
的简写:
/[0-9]+(,[0-9]+)*/