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

使用正则匹配含指定关键词的<a>标签失败,寻求解决方法

Fixing Your Regex to Match Tags with Target Keywords

Got it, let's break down why your current regex isn't catching that <a> tag and how to adjust it.

The Problem with Your Original Regex

Your regex:

/<a href="(.*)".*>(?:Refund|Refound|Refunds|return|returns)<\/a>/Ui

is looking for the exact keywords immediately after the closing > of the <a> tag with no other text in between. But your target tag has text like Shipping Return Policy—the keyword "Return" is buried in the middle of other content, so the regex skips over it.

Modified Regex That Works

Here's an adjusted version that will match the target tag (and any <a> where your keywords appear anywhere in the link text):

/<a href="(.*?)".*?>(.*?)(Refund|Refound|Refunds|return|returns)(.*?)<\/a>/Ui

Key Changes Made:

  • Non-greedy quantifiers (.*? instead of .*):
    • The original .* after href=" is greedy and might match across multiple tags if there are other <a> elements nearby. Using .*? stops at the first closing quote for the href.
    • We added .*? before and after your keyword group to allow any text (including none) to appear before or after the target keywords in the link text.
  • Flexible keyword placement: By wrapping the keyword group with .*?, we let the regex find your keywords anywhere inside the <a> tag's content, not just right after the opening tag.

Optional Optimization

You can simplify the keyword group to avoid repetition (thanks to the i flag for case insensitivity):

/<a href="(.*?)".*?>(.*?)(refund|refound|returns?)(.*?)<\/a>/Ui
  • returns? matches both "return" and "returns"
  • refund will match "Refund" and "Refunds" (since the i flag ignores case; you can add an s? if you want to be explicit: refunds?)

Testing It

If you plug this modified regex into your test tool, it should correctly match your target <a> tag:

<li class="site-footer__linklist-item"> <a href="/pages/shipping-return-policy">Shipping Return Policy</a> </li>

A Quick Note

While regex works for simple cases like this, keep in mind that HTML is not a regular language—for complex parsing, using an HTML parser library is always more reliable. But for this specific use case, the adjusted regex will do the trick.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:33:56