gpt4 book ai didi

javascript - 在 stable 前缀后面多次进行组捕获

转载 作者:行者123 更新时间:2023-11-27 23:24:48 25 4
gpt4 key购买 nike

是否可以创建一个正则表达式来检索与该类型的 html 输入匹配的所有捕获组:

<em>word1</em> <em>word2</em> <em>word3</em>
prefix: <em>word4</em> <em>word5</em>
<em>word6</em> <em>word7</em>

匹配

word4 word5

我尝试过 Lookahead 和 Lookbehind 零长度断言,但没有成功。

这是我的尝试

https://regex101.com/r/lA9xA3/2

但我确实知道如何让组在我的“前缀:”之后的每次出现时重复

非常感谢,

朱利安

最佳答案

您需要获取以前缀开头的行,然后获取 <em> 内的文本标签。

最好分两次完成,以免影响性能和可读性:

var re = /^prefix:((?: *<em>\w*\d*<\/em>)*) */gm; 
var str = 'prefix: <em>word1</em> <em>word2</em> <em>word3</em>\n<em>word4</em> <em>word5</em>\nprefix: <em>word6</em> <em>word7</em> <em>word8</em>';
var arr = [];

while ((m = re.exec(str)) !== null) {
var tmp = m[1].match(/[^<>]*(?=<\/em)/g); // Get matches inside EM
if (tmp) { // If there are any
tmp = tmp.filter(Boolean); // Remove empty array elements
for (var i=0; i<tmp.length;i++) {
arr.push(tmp[i]); // Add to resulting array
}
}
}
document.body.innerHTML = "<pre>" + JSON.stringify(arr, 0, 4) + "</pre>";

关于javascript - 在 stable 前缀后面多次进行组捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35048166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com