使用通配符匹配 URL
我正在尝试将带有通配符的 URL 与实际 URL 进行匹配。例如:
http://*google.com/*
需要匹配
http://maps.google.com
解决
http://www.google.com/maps
这个问题的最佳方法是什么?
我尝试过使用正则表达式,当我手动编程时效果很好,但我不确定是否可以动态生成正则表达式,或者这是否是这种情况下的最佳实践。
/(http|https):\/\/.*\.?google\.com\/?.*/i
非常感谢。
I'm trying to match URLs with wildcards in them to actual URLs. For example:
http://*google.com/*
Needs to match
http://maps.google.com
And
http://www.google.com/maps
What would be the best way of going about this?
I've tried using a regular expression and that works fine when I manually program it but I'm not sure whether it's possible to dynamically generate regular expressions or if that would be the best practice in this situation.
/(http|https):\/\/.*\.?google\.com\/?.*/i
Thanks very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将模式中所有出现的
*
替换为[^ ]*
- 它匹配零个或多个非空格字符的序列。因此
http://*google.com/*
将变为http://[^ ]*google.com/[^ ]*
这是一个正则表达式任务:
Replace all occurrences of
*
in the pattern with[^ ]*
- it matches a sequence of zero or more non-space characters.Thus
http://*google.com/*
will becomehttp://[^ ]*google.com/[^ ]*
Here is a regular expression to do the task:
如果您想查看一个经过良好测试的用于提取 URI 部分的库,我会查看 Google Closure Library 的 goog.uri.utils 方法。
https://github.com/ google/closure-library/blob/8e44fb343fff467938f9476ba7f727c6acac76d8/closure/goog/uri/utils.js#L187
这是执行繁重工作的正则表达式:
If you want to see a well tested library for extracting parts of a URI, I would check out Google Closure Library's goog.uri.utils methods.
https://github.com/google/closure-library/blob/8e44fb343fff467938f9476ba7f727c6acac76d8/closure/goog/uri/utils.js#L187
Here's the regex that does the heavy lifting: