【问题标题】:How can I pass parameter to regex constructor, and used in String.matchAll method [duplicate]如何将参数传递给正则表达式构造函数,并在 String.matchAll 方法中使用 [重复]
【发布时间】:2022-01-24 04:35:12
【问题描述】:

我想在字符串中搜索单词,假设我输入了单词“test”,它会返回所有匹配“test”的结果,但是我不知道如何将输入的单词传递给正则表达式构造函数。比如下图,如果我直接在matchAll中输入/\btest\b/g,那就没问题了,但是如果我想搜索不同的词怎么办,所以我尝试/\b${word}\b/g,但是不行。

您知道我可以使用的任何解决方案吗?提前致谢。

const word = "test";
const regex = `/\b${word}\b/g`;
const str = 'test1 test 2';
const array1 = [...str.matchAll(new RegExp(regex, "g"))];
const array2 = [...str.matchAll(new RegExp(/\btest\b/g, "g"))];

console.log(array1);
// expected output: Array ["test"] // however it return empty array []

console.log(array2);
// expected output: Array ["test"] // it do return expected result

【问题讨论】:

    标签: javascript arrays regex string


    【解决方案1】:

    您可以使用RegExp 构造函数,但您应该考虑到在使用构造函数时,正常的字符串转义规则(包含在字符串中时以\ 开头的特殊字符)是必要的。像这样:

    const word = "test";
    const regex = new RegExp(`\\b${word}\\b`, "g");
    const str = "test1 test 2";
    const array1 = [...str.match(regex)];
    
    console.log(array1);

    【讨论】:

    • 谢谢!我很笨,是的 \ 也应该包含在字符串中
    • 不客气。
    猜你喜欢
    • 1970-01-01
    • 2011-12-22
    • 2014-09-10
    • 2014-01-10
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多