【问题标题】:[javascript]-Regex code to input the text field not allowing to start with 0, but allow 0 and should not allow characters +,-, [closed][javascript]-Regex code to input the text field not allowing to start with 0, but allow 0 and should not allow characters +,-, [closed]
【发布时间】:2016-12-08 11:05:03
【问题描述】:

看,我正在寻找一个文本字段应该只接受这些的正则表达式代码

  1. 只有正整数
  2. 可以允许0
  3. 不应允许 +,-,。

不应该匹配:0345, 7., 7+, +7, .7, -7, 7-, ..7

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

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

【问题讨论】:

  • 您的意思是 + - . 或包括 ()
  • 它不应该接受 + - 。

标签: javascript regex


【解决方案1】:

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

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

【讨论】:

  • 谢谢!但是排除我提到的其他 3 个字符呢?
  • 这里是不允许的。你如何理解“排除”?
  • 我明白这一点,但它对我不起作用,这 3 个字符再次被接受。我不介意你把它弄复杂
  • 你看过演示吗?你如何测试验收?
  • @JohnRoshan 如果它对你不起作用,那么你做错了什么。这个正则表达式是正确的,并且会完全匹配你想要的。我添加了更多示例:regex101.com/r/NaTDIO/2 它表明它确实按预期工作。
【解决方案2】:

这对你有帮助吗

$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}`);
    });
}

【讨论】:

  • 这是一个 JavaScript 问题。
  • 谢谢,但我正在寻找正则表达式。
  • 您的代码只是搜索匹配项,它不会测试整个字符串是否匹配。因此它将允许两者之间不匹配的字符串。我也不明白为什么你有[1]。问题在哪里说数字 1 必须出现在每场比赛中?
猜你喜欢
  • 2022-12-02
  • 2013-12-16
  • 2022-12-01
  • 2022-12-01
  • 2020-09-13
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多