非贪婪正则表达式匹配、JavaScript 和 ASP
我需要进行非贪婪的匹配,希望有人可以帮助我。我有以下内容,并且我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要对子表达式匹配使用捕获括号:
Match 将返回一个数组,整个匹配位于索引 0 处,所有子表达式捕获将按照它们匹配的顺序添加到数组中。在本例中,索引
1
包含与\/pdf\/.*?\.pdf
匹配的部分。Try and make your regex more specific than just
.*?
if it's matching too broadly. For instance:[^"]+?
将延迟匹配不包含双引号字符的字符串。这会将匹配限制在引号内,因此匹配不会太宽在以下字符串中,例如:You need to use capturing parenthesis for sub-expression matches:
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:[^"]+?
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: