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

如何在javascript中标记带引号的字符串?

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

    标记由1个或多个空格分隔。 “带引号的字符串”是单个标记。 任何没有以引号开头的东西都是一种象征。 我尝试过但失败了:

    var tokenre = /"[^"]*"|[^"]\S+|\s\s*/g;
    

    例如,我想要这个输入

    [4,4]  "This is fun"
     2  2 +
     #
    

    标记化为

    ['[4,4]', '  ', '"This is fun"', '\n ', '2', '  ', '2', ' ', '+', '\n ', '#']
    

    可以使用以下代码进行测试:

    var result = null;
    do {
        result = tokenre.exec (program);
        console.log (result);
    } while (result != null);
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Wiktor Stribiżew    6 年前

    "..."

    s.match(/"[^"]*"|\S+|\s+/g)
    

    regex demo

    • "[^"]*" " "[^"\\]*(?:\\[\s\S][^"\\]*)*"
    • |
    • \S+
    • \s+

    var s = "[4,4]  \"This is fun\"\n2  2 +\n#";
    console.log(s.match(/"[^"]*"|\S+|\s+/g));