在 javascript 中获取引号中的字符串

Getting string in quotes in javascript

提问人:Return Cos 提问时间:4/3/2021 更新时间:4/4/2021 访问量:80

问:

如何编写一个函数来从字符串中获取引号中的所有字符串?该字符串可能包含转义引号。我尝试过正则表达式,但由于正则表达式没有类似状态的功能,我无法做到这一点。例:

apple banana "pear" strawberries "\"tomato\"" "i am running out of fruit\" names here"

应该返回一个数组,如['pear', '"tomato"', 'i am running out of fruit" names here']

也许分裂的东西可以工作,尽管我不知道如何。

JavaScript 解析 引号文字

评论

0赞 Stefan Haustein 4/3/2021
展示你的代码!在正则表达式中处理转义引号应该不是问题(基本上,你让它包含几乎任何以转义引号结尾的重复序列)
0赞 Return Cos 4/3/2021
@StefanHaustein但是,我怎样才能保留我是否在报价中或不在正则表达式中的信息?

答:

0赞 famoha 4/3/2021 #1

试试这个:

function getStringInQuotes(text) {

    const regex = const regex = /(?<=")\w+ .*(?=")|(?<=")\w+(?=")|\"\w+\"(?=")|(?<=" )\w+(?=")|(?<=")\w+(?= ")/g

    return text.match(regex);

}

const text = `apple banana "pear" strawberries "\"tomato\"" "i am running out of fruit\" names here"`;

console.log(getStringInQuotes(text));

评论

0赞 Return Cos 4/3/2021
这是我尝试过的方法,尽管它失败了,并且'apple"banana"hello"world"'''apple "banana" hello" world"'
0赞 famoha 4/3/2021
@ReturnCos 在问题中的例子中,你没有提到任何单一的报价。请分别更新问题。此外,添加其他示例,说明输入应该是什么以及输出应该是什么。这将有助于确定您真正想要实现的目标。
0赞 Return Cos 4/3/2021
我不需要单引号。我只是把它们用来表示字符串。忽略它们。
0赞 famoha 4/3/2021
@ReturnCos我更新了答案,当我测试它时,它得到了香蕉和你好,世界在你提到的两种情况下。一探究竟。
0赞 Return Cos 4/3/2021
失败apple "banana" hello" world"dasd"asdfasds"
1赞 Return Cos 4/4/2021 #2

我使用以下功能解决了这个问题:

const getStringInQuotes = (text) => {

    let quoteTogether = "";
    let retval = [];
    let a = text.split('"');
    let inQuote = false;
    for (let i = 0; i < a.length; i++) {
        if (inQuote) {
            quoteTogether += a[i];
            if (quoteTogether[quoteTogether.length - 1] !== '\\') {
                inQuote = false;
                retval.push(quoteTogether);
                quoteTogether = "";
            } else {
                quoteTogether = quoteTogether.slice(0, -1) + '"'
            }
        } else {
            inQuote = true;
        }
    }
    return retval;
}