You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写JavaScript正则表达式实现自定义标签间内容的多组匹配

问题原因

你当前使用的正则采用贪婪模式的*量词,会尽可能匹配最长的符合规则的内容,因此会从第一个{Keyword1}起始标签一直匹配到最后一个{\Keyword1}结束标签,最终得到一整段匹配结果。

调整方案

仅匹配Keyword1的正则写法

使用非贪婪量词*?配合全局匹配标志g即可实现分段匹配,需要命名分组的话JS环境下写法如下:
/{<strong>Keyword1<\/strong>}(?<Keyword1>[\s\S]*?) {<strong>\\Keyword1<\/strong>}/g
参数说明:

  • g:全局匹配标志,会检索所有符合规则的片段,而非仅返回第一个匹配结果
  • *?:非贪婪量词,匹配到最近的下一个{\Keyword1}结束标签就终止,不会向后贪婪匹配
  • (?<Keyword1>xxx):JS原生支持的命名分组语法,会将中间匹配到的内容存入Keyword1分组中

调用示例

const sampleText = `<p>Sample Text:</p>
<p>{<strong>Keyword1</strong>}words1 words1 words1{<strong>\\Keyword1</strong>}{<strong>Keyword2</strong>}words2 words2 words2{<strong>\\Keyword2</strong>}
{<strong>Keyword3</strong>}words3 words3 words3{<strong>\\Keyword3</strong>}{<strong>Keyword1</strong>}words4 words4 words4{<strong>\\Keyword1</strong>}
{<strong>Keyword2</strong>}words5 words5 words5{<strong>\\Keyword2</strong>}{<strong>Keyword1</strong>}words6 words6 words6{<strong>\\Keyword1</strong>}</p>`;

const regex = /{<strong>Keyword1<\/strong>}(?<Keyword1>[\s\S]*?) {<strong>\\Keyword1<\/strong>}/g;
const matches = [...sampleText.matchAll(regex)];

// 提取结果
const keyword1List = matches.map(item => item.groups.Keyword1);
console.log(keyword1List);
// 输出:["words1 words1 words1", "words4 words4 words4", "words6 words6 words6"]

通用多关键词匹配方案

如果需要同时匹配Keyword1、Keyword2、Keyword3等所有符合规则的标签内容,可以使用分组引用实现通用匹配:
/{<strong>(?<keyword>Keyword\d+)<\/strong>}(?<content>[\s\S]*?) {<strong>\\\k<keyword><\/strong>}/g
该正则会自动识别起始标签的关键词,匹配对应结束标签之间的内容,可一次性提取所有关键词对应的分段内容。


内容的提问来源于stack exchange,提问作者kevinbuiied

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:45:03