使用正则表达式查找数字中的特定数字

Find specific digit in a number using regular expression

本文关键字:数字 正则表达式 查找      更新时间:2023-09-26

我有一个具有特定值的变量,例如var no = 123056
有没有办法在RegExp的帮助下确定该数字是否包含数字 0

var no = 123056
var doesZeroExist = (no+"").indexOf('0') > -1;

尝试这样的事情。

var no = 12045;
var patt1=/0/; // search pattern
if (no.toString().match(patt1) !== null){
    // contains the character 0
    alert("character '0' found")
} else {
    // does not contain 0
    alert("'0' not found")
};

这是它的JSFiddle。

如果你真的想使用正则表达式,是的,有可能:

/0/匹配 0。将 0 替换为任何其他数字,包括 10+

/[035]/匹配 0、3 或 5 之一。将它们替换为您想要的任何数字。

如果需要数字序列,请在其后添加+

/(012)+/ 会将 1 与无限连续的 012 组匹配,例如 012、012012、012012012 ...

/012+/会将 01 和 1 匹配到无限数量的 2,例如 012、0122、01222 ...

此外,您可能想要使用的最佳正则表达式工具:http://www.debuggex.com/

var no='123056';
var regex=/0/;
if (no.match(regex) == 0) {
   alert('hey');
}

如果找到 0,这将为您提供警报消息。