代码之家  ›  专栏  ›  技术社区  ›  Vnuuk

Regex排除包含文件路径的url

  •  3
  • Vnuuk  · 技术社区  · 6 年前

    我正在尝试只匹配不包含 ? 查尔,这还没有结束 \ char,而不是以文件路径(.jpg、.aspx等-需要排除所有文件扩展名)

    这是预期的结果:

    1. http://mywebsite.com/some-path/test.jpg
    2. 不匹配- http://mywebsite.com/some-path/test.jpg/
    3. http://mywebsite.com/some-path/test
    4. 不匹配- http://mywebsite.com/some-path/test?v=ASAS77162UTNBYV77

    我的正则表达式- [^.\?]*[^/]*^[^?]*[^/]$ ,在大多数情况下效果良好,但在这方面失败 http://mywebsite.com/some-path/test.jpg (匹配,但不匹配)

    1 回复  |  直到 6 年前
        1
  •  2
  •   Tim Biegeleisen    6 年前

    以下模式似乎在起作用:

    ^(?!.*\?)(?!.*\/[^/]+\.[^/]+$).*[^/]$
    

    (?!.*\?)                - no ? appears anywhere in the URL
    (?!.*\/[^\/]+\.[^\/]+$) - no extension appears
    

    对于不以路径分隔符结尾的URL的要求是通过在URL的每一端匹配该字符来逐字给出的。

    console.log(/^(?!.*\?)(?!.*\/[^/]+\.[^/]+$).*[^/]$/.test('http://mywebsite.com/some-path/test'));
    console.log(/^(?!.*\?)(?!.*\/[^/]+\.[^/]+$).*[^/]$/.test('http://mywebsite.com/some-path/test.jpg'));
    console.log(/^(?!.*\?)(?!.*\/[^/]+\.[^/]+$).*[^/]$/.test('http://mywebsite.com/some-path/test?v=ASAS77162UTNBYV77'));
    console.log(/^(?!.*\?)(?!.*\/[^/]+\.[^/]+$).*[^/]$/.test('http://mywebsite.com/some-path/test.jpg/'));