假设我有一个类似'there goes "something here", and "here" and I have "nothing else to say"'
的字符串。
我需要一个正则表达式来准确检索['something here', 'here', 'nothing else to say']
。请注意,结果不是用引号引起来的,这是因为我不想在每次比赛中再次致电replace(/"/g, '')
。
作为参考,
'there goes "something here", and "here" and I have "nothing else to say"'.match(/".*?"/g)
给我这个:
['"something here"', '"here"', '"nothing else to say"']
但是,就像我说的那样,我不希望结果用引号引起来,并对每个结果进行replace
调用。
答案 0 :(得分:1)
这应该有效 "([^"]*)"
这是一个示例测试:
https://regex101.com/r/CjK2fp/1
答案 1 :(得分:0)
何时在第一个引号后加上\w
:
string = 'there goes "something here", and "here" and I have "nothing else to say"';
regexp = /(?<=")\w.*?(?=")/g
result = string.match(regexp);
console.log(result);
请注意引号和内容之间应留有间隔:
let string = 'there goes " something here ", and "here" and I have "nothing else to say"';
function everyOther(string) {
let regexp = /(?<=").*?(?=")/g
let answerArray = [];
for (; ; ) {
if (regexp.lastIndex !== 0) {
regexp.lastIndex += 2;
}
let matchArr = regexp.exec(string);
if (regexp.lastIndex === 0) {
break;
}
let match = matchArr[0]
answerArray.push(match);
}
console.log(answerArray);
}
everyOther(string);
答案 2 :(得分:0)
通过使用一些最新的JS功能
let reg = /"(.*?)"/gi;
let results = str.matchAll(reg);
// results - is not an array, but an iterable object
// convert results to an Array
results = Array.from(results);
// using map method to get second items from each array item
// which is a captured group
results = results.map(item => item[1]);