【问题标题】:RegEx for passing space and single quote用于传递空格和单引号的正则表达式
【发布时间】:2019-10-14 10:38:25
【问题描述】:

我对 RegEx 还很陌生,在让我的 RegEx 做我想做的事情时遇到了一些问题。我正在尝试创建一个正则表达式,以防止除单引号 (')、破折号 (-) 和句点 (.) 之外的任何特殊字符。 RegEx 需要允许空格和空字符串。

我现在拥有的是:

^[a-zA-Z0-9-.]*$

我需要添加什么才能使其正常工作,例如“Kevin O'Leary”这个名字?

我尝试通过添加 \s 来允许空格,但它破坏了我的 RegEx 的其他部分。

^[a-zA-Z0-9-.]*$

预期:应该允许像 Kevin O'Leary 这样的名字 实际:不允许像 Kevin O'Leary 这样的名字

【问题讨论】:

  • 确保将连字符放在[ ] 中的第一个或最后一个,否则它具有“范围”含义。不要忘记列出报价。

标签: javascript regex string regex-greedy


【解决方案1】:

您可以使用i 标志并使用此表达式:

^[a-z0-9'-.\s]+$

其中\x27'\s 是空格。

const regex = /^[a-z0-9'-.\s]+$/gmi;
const str = `Kevin O'Leary`;
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}`);
    });
}

DEMO

正则表达式

如果不需要此表达式,可以在 regex101.com 中修改/更改。

正则表达式电路

jex.im 可视化正则表达式:

【讨论】:

  • Invalid range end in character class ^[a-z0-9-<<<HERE>>>.\x27\s]+$ 以及,为什么在 \x27 类中使用字节构造?
  • 我将把编辑留给所有者。对我来说,除非需要神秘,否则字节符号很难阅读Invalid range end in character class ^[\x09-\x0d\x1C-\x20\x61-\x7a\x30-\x39-<<<HERE>>>\x2e\x27\x85}\xa0\x{1680}\x{2000}-\x{200a}\x{2028}-\x{2029}\x{202f}\x{205f}\x{3000}]+$
【解决方案2】:

只需在字符范围内添加引号和空格:

^[ a-zA-Z0-9'.-]*$

空格可以只是模式中的文字空格。此外,您需要将- 作为最后一个符号,因为它在范围内具有特殊含义。

regex101 demo

【讨论】:

  • 谢谢。我感谢您的帮助! @ruohola
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-27
  • 1970-01-01
  • 2022-01-23
  • 2013-09-16
  • 2020-05-17
  • 1970-01-01
  • 2012-12-05
相关资源
最近更新 更多