获取与正则表达式的字符串

问题描述 投票:1回答:4

我有这样的命令:add "first item" and subtract "third course", disregard "the final power".

我如何提取所有的字符串,因此输出数组:["first item", "third course", "the final power"]

javascript arrays regex
4个回答
2
投票

尝试使用匹配quotetextquote正则表达式,然后使用map删除所拍摄的报价:

const string = 'add "first item" and subtract "third course", disregard "the final power".';

const quotes = string.match(/\"(.*?)\"/g).map(e => e.split("\"")[1]);

console.log(quotes);

1
投票

一种解决方案是使用这样的全局RegExp,只是环通

var extractValues = function(string) {
    var regex = /"([^"]+)"/g;
    var ret = [];
    for (var result = regex.exec(string);
            result != null;
            result = regex.exec(string)) {
        ret.push(result[1]);
    }
    return ret;
}
extractValues('add "first item" and subtract "third course", disregard "the final power".')

但是请注意,如此,大部分的答案,包括这一个,不处理的事实,值可能在他们的报价。因此,例如:

var str = 'This is "a \"quoted string\""';

如果你有这样的数据集中的,你需要适应一些答案。


0
投票

您可以使用此

“[^”] +“? - 匹配的POI随后除qazxsw POI(一个或多个时间懒惰模式)的任何qazxsw随后"

"

0
投票
"

参考:let str = `add "first item" and subtract "third course", disregard "the final power"` let op = str.match(/"[^"]+?"/g).map(e=>e.replace(/\"/g, '')) console.log(op)

© www.soinside.com 2019 - 2024. All rights reserved.