【问题标题】:.split() at spaces and quotation marks, keep quotation marks - Regex/Javascript.split() 在空格和引号处,保留引号 - 正则表达式/Javascript
【发布时间】:2020-05-17 16:13:54
【问题描述】:

我想从一个字符串返回一个数组。该数组应包含所有字符作为单独的元素,除了空格。我当前的正则表达式如下所示:

str = 'Stuff in "quotation marks"';
arr = str.split(/(?=["])|[\s+]/);
console.log(arr);
// [ 'Stuff', 'in', '"quotation', 'marks', '"' ]

我希望它返回如下内容:

// [ 'Stuff', 'in', '"', 'quotation', 'marks', '"' ]

我可以使用什么正则表达式将 '"quotation' 前面的 " 作为数组中的单独元素返回?

【问题讨论】:

    标签: javascript arrays regex split


    【解决方案1】:

    你可以使用String.prototype.match()MDN

    const str = 'Stuff in "quotation marks"';
    const arr = str.match(/\w+|"/g);
    console.log(arr);

    PS:注意\w[a-zA-Z0-9_] 类似


    您也可以在字边界处.split(/\b/) /\b/,但要修剪并过滤掉数组中的空值:

    const str = 'Stuff in "quotation marks"';
    const arr = str.split(/\b/).map(w=>w.trim()).filter(w=>w);
    console.log(arr);

    免责声明:上述示例不适用于 š、ç 等特殊字符...

    【讨论】:

    • ['"] - 我想也可以匹配单引号。
    • @RyanWheale 好吧...不确定 OP 的确切用例是什么。但是说你有Let's,我宁愿把它保留为一个词。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多