[英]Getting string in quotes in javascript
如何编写 function 以从字符串中获取引号中的所有字符串? 该字符串可能包含转义引号。 我已经尝试过正则表达式,但由于正则表达式没有 state 之类的功能,我无法做到这一点。 例子:
apple banana "pear" strawberries "\"tomato\"" "i am running out of fruit\" names here"
应该返回一个数组,如['pear', '"tomato"', 'i am running out of fruit" names here']
也许有 split 的东西可以工作,虽然我不知道怎么做。
我使用以下 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;
}
尝试这个:
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.