使用正则匹配含指定关键词的<a>标签失败,寻求解决方法
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
.*afterhref="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.
- The original
- 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"refundwill match "Refund" and "Refunds" (since theiflag ignores case; you can add ans?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

