简体   繁体   English

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

[英]Getting string in quotes in javascript

How may I write a function to get all the strings in quotes from a string?如何编写 function 以从字符串中获取引号中的所有字符串? The string may contain escaped quotes.该字符串可能包含转义引号。 I've tried regex but as regex does not have a state like feature, I wasn't able to do that.我已经尝试过正则表达式,但由于正则表达式没有 state 之类的功能,我无法做到这一点。 Example:例子:

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

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

Maybe something with split can work, though I can't figure out how.也许有 split 的东西可以工作,虽然我不知道怎么做。

I solved this problem using the following function:我使用以下 function 解决了这个问题:

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;
}

Try this:尝试这个:

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM