不带尾斜杠且无文件扩展名的URL匹配正则表达式

4

我已经读了很多关于正则表达式的文章,但是仍然感到非常困惑。

我想匹配第一个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

2个回答

7

使用

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

请查看 证明

解释

--------------------------------------------------------------------------------
  ^                        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

3
所有的SO答案都应该像这样,谢谢。 - Learner For-life
@LearnerFor-life 完全同意,看到这样的答案真是太好了! - Jorge Morgado

0

如果你确定只匹配URL,你也可以反转URL并使用:

^\w+\/
  • ^ 只匹配开头(在这种情况下是结尾)
  • \w+ 匹配至少一个字母数字字符集合
  • \/ 匹配斜杠

在Python中,代码如下:

re.search(r'^\w+\/', url[::-1])

如果这不是 None,那么url 以这样的方式结束:.../someword

注意: 这仅适用于确定 url 确实是一个URL的情况。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接