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

Javascript:删除字符串标点并拆分为单词?

  •  2
  • MysteryPancake  · 技术社区  · 6 年前

    很抱歉,如果之前有人问过这个问题,我会尝试从如下字符串中获取单词数组:

    "Exclamation! Question? \"Quotes.\" 'Apostrophe'. Wasn't. 'Couldn't'. \"Didn't\"."
    

    阵列应如下所示:

    [
      "exclamation",
      "question",
      "quotes",
      "apostrophe",
      "wasn't"
      "couldn't",
      "didn't"
    ]
    

    当前我正在使用以下表达式:

    sentence.toLowerCase().replace(/[^\w\s]/gi, "").split(" ");
    

    问题是,它删除了像“was not”这样的撇号,将其变成了“wasnt”。

    我不知道怎样在这样的词中保留撇号。

    任何帮助都将不胜感激!

    var sentence = "Exclamation! Question? \"Quotes.\" 'Apostrophe'. Wasn't. 'Couldn't'. \"Didn't\".";
    console.log(sentence.toLowerCase().replace(/[^\w\s]/gi, "").split(" "));
    2 回复  |  直到 6 年前
        1
  •  4
  •   revo shanwije    6 年前

    围绕您自己的解决方案工作可能会很棘手,但您可以这样考虑撇号:

    sentence = `"Exclamation! Question? \"Quotes.\" 'Apostrophe'. Wasn't. 'Couldn't'. \"Didn't\"."`;
    console.log(
        sentence.match(/\w+(?:'\w+)*/g)
    );

    注意:量词已从 ? * 允许多个 ' 一句话。

        2
  •  1
  •   Jeto    6 年前

    @revo的答案看起来不错,这里还有另一个应该也适用的选项:

    const input = "Exclamation! Question? \"Quotes.\" 'Apostrophe'. Wasn't. 'Couldn't'. \"Didn't\".";
    console.log(input.toLowerCase().match(/\b[\w']+\b/g));

    说明:

    • \b 匹配词的开头/结尾,
    • [\w']+ 匹配字母、数字、下划线或引号(要省略下划线,可以使用 [a-zA-Z0-9'] 相反,
    • /g 告诉正则表达式捕获与该模式匹配的所有事件(而不仅仅是第一个)。