使用类似于正则表达式但特定于 URL 的语言来匹配 URL 中的模式

发布于 2024-08-21 14:22:55 字数 245 浏览 9 评论 0原文

我在代码的一部分中使用了匹配的 URL。现在我为此使用正则表达式。这很好,但并不总是产生“好的”、简单可读的模式。是否有定义匹配 URL 的语言?它应该是这样的:http://*.example.com/* 所以简单的通配符和对 URL 有用的东西就在那里。

如果这些表达式可以简单地转换为正则表达式,那就最好了。你知道这种语言的规范吗?甚至知道它的实现吗?最好是 ruby​​。否则我自己实现它……关键是模式的可读性。感谢您的帮助!

I use matching URLs in a part of my code. Now I use regular expressions for this. This is fine, but does not always produces "nice", simply readable patterns. Is there any language defined for matching URLs? It should be like this: http://*.example.com/* so simply wild-cards and things useful for URL would be there.

The best would if these expression can be simply transformed to regexp. Do you know specification for such a language, or even an implementation, preferably for ruby.. otherwise I implement it myself... the key is the readability of the patterns. Thanks for help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

嘿嘿嘿 2024-08-28 14:22:55

在开始之前,您必须仔细计算语法。乍一看,通过将语法转换为普通的正则表达式可以轻松实现您的意图:

s = 'http://*.example.com/*' #=> "http://*.example.com/*"
r = Regexp.compile("^#{Regexp.escape(s).gsub('\*','.*')}$") #=> http:examplecom
'http://test.example.com/path/to/doc.html' =~ r #=> 0
'http://test.example2.com/path/to/doc.html' =~ r #=> nil

You'd have to carefully work your syntax out before you begin. At first glance, what you intend would be easily achieved by translating your syntax into ordinary regexes:

s = 'http://*.example.com/*' #=> "http://*.example.com/*"
r = Regexp.compile("^#{Regexp.escape(s).gsub('\*','.*')}$") #=> http:examplecom
'http://test.example.com/path/to/doc.html' =~ r #=> 0
'http://test.example2.com/path/to/doc.html' =~ r #=> nil
太阳男子 2024-08-28 14:22:55

正确解析 URL 可能有点棘手,特别是如果您想符合标准的话。这就是 Ruby 具有 uri 内置库的原因。

对于带有您想要的占位符的更高级解析库,您应该查看 可寻址 gem。

URLs can be a bit tricky to parse correctly, especially if you want to be standards compliant. This is why Ruby has the uri builtin library.

For a more advanced parsing library with placeholders like you want, you should look into the addressable gem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文