首页 > 解决方案 > 正则表达式匹配 URL 中的文件扩展名

问题描述

我有以下带有测试用例的正则表达式regex101

.{0,}(\.jpg|\.gif).{0,}

我想在 URL 的末尾匹配包含 .gif 和 .jpg 扩展名的 URL。不幸的是,该域被命名为 gif.com。

这是我的测试用例:

1 - http://www.gif.com/test.jpg - should match
2 - http://www.gif.com/test.html - shouldn't match
3 - http://gif.com/test.jpg - should match
4 - http://gif.com/test.html - shouldn't match

我想将正则表达式更改为在案例 2 中不匹配。我尝试了一些负面的http://www后向查找,但我需要正则表达式来匹配整行。

标签: javaregex

解决方案


您需要使用$锚点,这意味着字符串的结尾

.{0,}(\.jpg|\.gif)$

Regex Demo


推荐阅读