【问题标题】:RegEx for Javascript to strict alphanumeric with optional space charecter用于 Javascript 的 RegEx 到带有可选空格字符的严格字母数字
【发布时间】:2019-06-28 01:58:13
【问题描述】:

我需要找到一个只允许字母数字的 reg ex。它应该只接受字母数字字符。我正在尝试使用正则表达式,它传递了除可选空间之外的所有情况。

dGgs1s23 - valid

12fUgdf  - valid,

123 abc  - Invalid,

121232   - invalid,

abchfe   - invalid,

 abd()*  - invalid, 

42232^5$ - invalid

正则表达式处理所有情况,除了“abc 123”之间有空格。

^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$

有人可以建议修改上述正则表达式吗?

重要提示:应允许可选的空格字符以及严格的字母数字输入。

【问题讨论】:

  • 无法重现 - 看起来您的正则表达式成功拒绝了 regex101 上的 123 abc 并且符合您对其他所有内容的期望。你能澄清一下问题吗?
  • 有一个可选空格的正则表达式就是^(?=.*[a-zA-Z])(?=.*[0-9])[ a-zA-Z0-9]+$
  • 如果你需要空格在中间,如果它是一个空格,那就是^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*$,或者如果中间有很多空格,那就是^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9](?: +[a-zA-Z0-9]+)*$

标签: javascript regex


【解决方案1】:

我的猜测是,也许这个表达式会验证我们想要的数据:

^(?=.*[a-z].*)(?=.*[0-9].*)([a-z0-9]+|[a-z]+\s[0-9]+)$

Demo

测试

const regex = /^(?=.*[a-z].*)(?=.*[0-9].*)([a-z0-9]+|[a-z]+\s[0-9]+)$/gmi;
const str = `dGgs1s23
12fUgdf
abcd1
1abcd
abc 123

abc  123
123 abc
121232
abchfe
abd()*
42232^5\$`;
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}`);
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多