非贪婪正则表达式匹配、JavaScript 和 ASP

发布于 2024-08-24 22:20:56 字数 211 浏览 5 评论 0原文

我需要进行非贪婪的匹配,希望有人可以帮助我。我有以下内容,并且我正在使用 JavaScript 和 ASP

match(/\href=".*?\/pdf\/.*?\.pdf/)

上面的匹配,匹配 href 标记的第一个开头。我需要它仅匹配 /pdf/ 文件夹中的最后一个 href。

有什么想法吗?

I need to do a non greedy match and hope someone can help me. I have the following, and I am using JavaScript and ASP

match(/\href=".*?\/pdf\/.*?\.pdf/)

The above match, matches the first start of an href tag. I need it to only match the last href that is part of the /pdf/ folder.

any ideas ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

诗笺 2024-08-31 22:20:56

您需要对子表达式匹配使用捕获括号:

match(/\href=".*?(\/pdf\/.*?\.pdf)/)[1]; 

Match 将返回一个数组,整个匹配位于索引 0 处,所有子表达式捕获将按照它们匹配的顺序添加到数组中。在本例中,索引 1 包含与 \/pdf\/.*?\.pdf 匹配的部分。


Try and make your regex more specific than just .*? if it's matching too broadly. For instance:

match(/\href="([^"]+?\/pdf\/[^\.]+?\.pdf)"/)[1];

[^"]+? 将延迟匹配不包含双引号字符的字符串。这会将匹配限制在引号内,因此匹配不会太宽在以下字符串中,例如:

<a href="someurl/somepage.html">Test</a><a href="dir/pdf/file.pdf">Some PDF</a>

You need to use capturing parenthesis for sub-expression matches:

match(/\href=".*?(\/pdf\/.*?\.pdf)/)[1]; 

Match will return an array with the entire match at index 0, all sub expression captures will be added to the array in the order they matched. In this case, index 1 contains the section matching \/pdf\/.*?\.pdf.


Try and make your regex more specific than just .*? if it's matching too broadly. For instance:

match(/\href="([^"]+?\/pdf\/[^\.]+?\.pdf)"/)[1];

[^"]+? will lazily match a string of characters that doesn't contain the double quote character. This will limit the match to staying within the quotes, so the match won't be too broad in the following string, for instance:

<a href="someurl/somepage.html">Test</a><a href="dir/pdf/file.pdf">Some PDF</a>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文