首页 > 解决方案 > 不要在正则表达式中捕获可选的 html 标记

问题描述

我想解析团队的名称。但正如您在下图中看到的最后两行没有<a>标签。我的正则表达式代码也选择<a>. 如何避免这种情况?

HTML

<td class="team2"><a class="black" href="/team/test/">Test team</a></td>
<td class="team3"><a class="black" href="/team/test/">Opponent team</a></td>
<td class="team2">Test team</td>
<td class="team3">Opponent Team</td>

正则表达式

<td class="team\d">(<a class="black" href=".+">)?(.+)(<\/a>)?<\/td>

在此处输入图像描述

标签: regex

解决方案


您的原始表达式很棒,只是缺少一个(?),我们将添加它并稍微简化为:

<td(.+?)>(<a(.+?)>)?(.+?)(<\/a>)?<\/td>

演示

正则表达式电路

jex.im可视化正则表达式:

在此处输入图像描述

const regex = /<td(.+?)>(<a(.+?)>)?(.+?)(<\/a>)?<\/td>/gm;
const str = `<td class="team2"><a class="black" href="/team/test/">Tést team</a></td>
<td class="team3"><a class="black" href="/team/test/">opponent team</a></td>
<td class="team2">test team</td>
<td class="team3">my  team</td>`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}


推荐阅读