【问题标题】:Uncaught SyntaxError: Invalid regular expression: /@|#|$|&|*/: Nothing to repeat [duplicate]未捕获的 SyntaxError:无效的正则表达式:/@|#|$|&|*/:没有可重复的内容 [重复]
【发布时间】:2019-07-26 07:08:50
【问题描述】:

我必须编写只需要选择一些特殊字符的正则表达式。我在下面写了

samplem - https://regexr.com/4i59r

但是当我尝试像下面这样启动它时,它会抛出以下错误:

var SPECIAL_CHAR = new RegExp('\@|\#|\$|\&|\*', 'g');

我做错了吗?

【问题讨论】:

  • 您需要对反斜杠进行双重转义,因为您提供了一个 string,因此您的实际正则表达式最终(基本上)是 /@|#|$|&|*/g
  • 或者使用字符类[@#$&]。如果要匹配多个使用[@#$&]+
  • 嗨@Thefourthbird,感谢您的回答。发布它我会接受
  • 嗨,我喜欢这个regexr.com/4i5ps,但我想删除“引号

标签: javascript regex


【解决方案1】:

你可以试试这个。

const regex = /\@|\#|\$|\&|\*/gm;
const str = `"name"@#
#
\$
&`;
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}`);
    });
}

【讨论】:

    【解决方案2】:

    你必须双重转义*,第一个反斜杠将在字符串中转义,第二个将在正则表达式中转义

    var SPECIAL_CHAR = new RegExp('\@|\#|\$|\&|\\*', 'g');

    不要忘记反斜杠也用于转义 javascript 字符串文字中的单个字符:

    var x = '\*';
    
    
    console.log(x); // *

    【讨论】:

    • 你还需要转义$,除非是为了匹配行尾
    猜你喜欢
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    相关资源
    最近更新 更多