我有一个字符串:
"My cow gives milk, my cow always gives milk".
我想提取"cow"
和"milk"
之间的文本,这将给我
["gives", "always gives"].
我已经尝试过string.match('cow (.*?) milk')
,但是它给了我
["cow gives milk", "gives"].
答案 0 :(得分:3)
您可以使用matchAll,然后仅参加分组
let str = "My cow gives milk, my cow always gives milk"
let op = str.matchAll(/cow (.*?) milk/g)
let final = [...op].map( value => value[1] )
console.log(final)
替代
const regexp = RegExp('cow (.*?) milk','g');
const str = "My cow gives milk, my cow always gives milk"
while ((matches = regexp.exec(str)) !== null) {
console.log(`Matched value :- ${matches[1]}`);
}
答案 1 :(得分:1)
您可以使用
str.match(/(?<=cow)((?!milk).)*(?=milk)/gs)
(?<=cow)
:了解母牛的情况
((?!milk).)*
:除“牛奶”外,什么都可以得到。
(?=milk)
:停止喝牛奶