在 javascript 中获取引号中的字符串
Getting string in quotes in javascript
我如何编写一个函数来从一个字符串中获取引号中的所有字符串?该字符串可能包含转义引号。我试过正则表达式,但由于正则表达式没有类似状态的功能,所以我无法做到这一点。示例:
apple banana "pear" strawberries "\"tomato\"" "i am running out of fruit\" names here"
应该return像['pear', '"tomato"', 'i am running out of fruit" names here']
这样的数组
也许有 split 的东西可以工作,虽然我不知道如何。
试试这个:
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));
我使用以下函数解决了这个问题:
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;
}
我如何编写一个函数来从一个字符串中获取引号中的所有字符串?该字符串可能包含转义引号。我试过正则表达式,但由于正则表达式没有类似状态的功能,所以我无法做到这一点。示例:
apple banana "pear" strawberries "\"tomato\"" "i am running out of fruit\" names here"
应该return像['pear', '"tomato"', 'i am running out of fruit" names here']
也许有 split 的东西可以工作,虽然我不知道如何。
试试这个:
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));
我使用以下函数解决了这个问题:
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;
}