首页 > 解决方案 > 正则表达式搜索因特殊字符而失败

问题描述

我正在尝试在 JavaScript 中进行正则表达式搜索,但它不适用于特殊字符,例如$and +

var string = "Keto After 50 $20 CPA+FS";
string.search(/Keto After 50 $20 CPA F+S/g);

我期望匹配和结果为 0 而不是 -1。

标签: javascriptregex

解决方案


欢迎!

我们可能只想逃避 metachars:

(Keto After 50 \$20 CPA\+FS)

测试

const regex = /(Keto After 50 \$20 CPA\+FS)/gm;
const str = `Keto After 50 \$20 CPA+FS`;
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}`);
    });
}

请参阅此演示以获取更多信息。


推荐阅读