【问题标题】:Regex for finding custom URLs用于查找自定义 URL 的正则表达式
【发布时间】:2017-04-26 16:16:48
【问题描述】:

我想创建一个正则表达式来匹配以 http://、https://、// 开头的 URL,或者查找扩展名不同于 html、htm、php 和 php3 的 URL。 URL 查询子字符串是可选的

假设我想找到这些:

http://example.com
/example.mp3
/example.mp3?q=example
http://example.com/example.mp3
#example

并拒绝这些:

example
/example
/example/
/example.htm
/example.htm?q=example
/example.mp3/example //The .mp3 needs to be extension to be accepted
/example#example

我已经尝试过/(^(http:\/\/|https:\/\/|\/\/|#)|(.*)((.*)\.^(?!html|htm|php|php3)$)(\?.*)?$)/igm,但没有成功。

如果相反(颠倒接受和拒绝列表)更容易做到,即使这非常感谢,我可以更改处理正则表达式的函数。

【问题讨论】:

  • 不清楚为什么要找#example而不是/example#example
  • 您的示例和接受参数的描述略有不同。您要接受/ 还是//
  • @Oriol #example 可以是同一页面中某个 id 的锚点,/example#example 可以是另一个页面中某个 id 的锚点
  • @wizebin 我不想接受//(跨域)并接受/(同源)
  • @WiktorStribiżew 非常感谢!效果很好!

标签: javascript regex url


【解决方案1】:

看来你可以用

^(?:#.+|(?:https?:/)?/[^?#\n]*\.(?!(?:html?|php3?)\b)\w+(?:\?.*)?)$

regex demo

模式详情

  • ^ - 字符串开头
  • (?:#.+ - # 后跟任意 1+ 个字符
  • | - 或
  • (?:https?:/)?/[^?#\n]*\.(?!html?|php3?)\w+(?:\?.*)?) -
    • (?:https?:/)?/ - 一个可选的http:/https:/ 然后/
    • [^?#]* - 除了 ?# 之外还有 0+ 个字符
    • \. - 一个点
    • (?!(?:html?|php3?)\b)\w+ - 1 个或多个不等于 htmhtmlphpphp3 的字母/数字/下划线
    • (?:\?.*)?) - 一个可选的 ? 后跟任何 0+ 字符
  • $ - 字符串结束

【讨论】:

  • 感谢您的回答!代码乍一看似乎有点难,但解释让我更好地理解了代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多