代码之家  ›  专栏  ›  技术社区  ›  Andrew

正则表达式javascript中的转义问号

  •  69
  • Andrew  · 技术社区  · 17 年前

    我认为这是一个简单的问题。

    我尝试在JavaScript中使用正则表达式搜索另一个字符串中出现的字符串,如下所示:

     var content ="Hi, I like your Apartment. Could we schedule a viewing? My phone number is: ";
    
     var gent = new RegExp("I like your Apartment. Could we schedule a viewing? My", "g");
    
     if(content.search(gent) != -1){   
         alert('worked');     
     }          
    

    ? 角色…我试着用 \ ,但这也不起作用。还有其他的使用方法吗 ?

    4 回复  |  直到 11 年前
        2
  •  27
  •   Christian C. Salvadó    17 年前

    应使用双斜杠:

    var regex = new RegExp("\\?", "g");
    

    \ 也用于转义字符串中的字符,因此“\?”变为: "?"

    和 "\\?" ,成为 "\?"

        3
  •  16
  •   jiggy    17 年前

    var gent = /I like your Apartment. Could we schedule a viewing\?/g;
    
        4
  •  6
  •   Wiktor Stribiżew    6 年前

    每当你有一个 模式(即不使用变量来构建RegExp),使用 只需使用 仅有一个的

    var re = /I like your Apartment\. Could we schedule a viewing\?/g;
                                   ^^                            ^^
    

    每当需要动态构建RegExp时,请使用 RegExp 构造函数表示法 你必须去的地方

    var questionmark_block = "\\?"; // A literal ?
    var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot
    var re = new RegExp(initial_subpattern + questionmark_block, "g");
    

    如果你使用 String.raw 您可以使用的字符串文本 \ 原样(请参见使用模板字符串文字的示例,其中可以将变量放入正则表达式模式中):

    const questionmark_block = String.raw`\?`; // A literal ?
    const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
    const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
    console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g

    A必须阅读: RegExp: Description 在MDN。

    推荐文章