regex - 不要在正则表达式中捕获可选的 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>
解决方案
您的原始表达式很棒,只是缺少一个(?
),我们将添加它并稍微简化为:
<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}`);
});
}
推荐阅读
- javascript - 如何修复 jQuery.Deferred 异常:无法读取未定义的属性“顶部”类型错误:无法读取未定义的属性“顶部”
- javascript - 我需要导出到节点 post rout 的脚本标签中的数据
- react-native - 超过 React Native 插值最大调用堆栈大小
- vba - 使用 VBA 自动更新多个文档中的同名部分
- amazon-web-services - CodePipeline 任务修订正在为 ECS Fargate 服务创建,即使我没有更改任何任务定义
- python - 如何在 django 中开发两个导致一个详细视图的列表视图?
- c - 程序以代码退出:5 - 使用 gcc 的 Geany
- javascript - 如何让 Material UI React Textfield 不被文本覆盖,当它具有粘性并且已向上滚动时?
- python - 如何在 ZeroMQ python 中正确声明套接字类型?
- symfony - Symfony 表单:表单类型字段的集合不映射