javascript正则表达式允许数字和特定的特殊字符

时间:2018-03-05 15:19:52

标签: javascript regex

我正在尝试使用正则表达式来检查数字和逗号,例如

这将通过

abc
1,,3,,4
1,3,
,1,1

这不会通过

/[0-9]*[,][0-9]*/

我现在的正则表达式是

{{1}}

它似乎不像我想要的那样工作 我能得到一些帮助吗

5 个答案:

答案 0 :(得分:2)

你可以使用这样的正则表达式:

^\d+(,\d+)*$

<强> Working demo

答案 1 :(得分:1)

正则表达式^\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))
}

答案 2 :(得分:1)

使用此正则表达式^([0-9]+,)*[0-9]+$

&#13;
&#13;
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");
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

这不是正则表达式,但这是一种方法:

// 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);

答案 4 :(得分:0)

您当前的正则表达式:/[0-9]*[,][0-9]*/ 会匹配 ,

1,1

,6

4953,5433

5930,

假设您要匹配以逗号分隔的数字列表(每个数字都包含任意数字), 你需要: /\d+(,\d+)*/ 其中\d[0-9]的简写:

/[0-9]+(,[0-9]+)*/

相关问题