[javascript] -Regex代码输入文本字段,不允许以0开头,但允许0,不应该允许字符+, - ,

时间:2016-12-08 11:05:03

标签: javascript regex

请参阅,我正在寻找一个正则表达式代码,其中文本字段应该只接受这些

  1. 只有正整数
  2. 可以允许0
  3. 不应该允许+, - ,。
  4. 它不应该匹配:0345,7。,7 +,+ 7,.7,-7,7-,。7

    不得接受: 1. + 2. - 3.

    注意:我不想要按键功能,我正在寻找正则表达式

2 个答案:

答案 0 :(得分:1)

使用此:^(0|[1-9][0-9]*)$

演示:https://regex101.com/r/NaTDIO/1

答案 1 :(得分:0)

这是否有任何帮助

$re = '/([1]\d+)/';
$str = '0123';

preg_match_all($re, $str, $matches);

// Print the entire match result
print_r($matches);

现在是等效的JavaScript

const regex = /([1]\d+)/g;
const str = `0123`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}