首页 > 解决方案 > 正则表达式匹配没有斜杠的 URL,也没有文件扩展名

问题描述

到目前为止,我对阅读这么多关于此的正则表达式文章感到非常困惑。

我希望匹配第一个 URL,其余的不应匹配:

https://subdomain.example.com/test <== only this should match
https://subdomain.example.com/paht/test.css
https://subdomain.example.com/path/path/test.js
https://example.com/test/

我希望仅匹配没有尾部斜杠或文件扩展名的路由。

这是我的正则表达式:https:.*^(?!([^\/]|(\.[a-z]{2,8})))$

你可以在这里试试:https ://regexr.com/5dic8

标签: regex

解决方案


Use

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

See proof

Explanation

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  http                     'http'
--------------------------------------------------------------------------------
  s?                       's' (optional (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  :                        ':'
--------------------------------------------------------------------------------
  \/                       '/'
--------------------------------------------------------------------------------
  \/                       '/'
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    \/                       '/'
--------------------------------------------------------------------------------
  )?                       end of grouping
--------------------------------------------------------------------------------
  [^\/.]+                  any character except: '\/', '.' (1 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

推荐阅读