在 .NET 中查找 URL?
给定一个字符串列表,我有兴趣查找哪些是有效的 http://
URL。我的第一种方法是使用正则表达式并执行如下操作:
var urls = strs.Where(str => urlRegex.matches(str));
是否有更惯用/自然/简单的方法怎么办?
Given a list of strings, I'm interested in finding which ones are valid http://
URLs. My first approach would be to use a regex and do something like this:
var urls = strs.Where(str => urlRegex.matches(str));
Is there a more idiomatic/natural/simple way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,我会使用 Uri.TryCreate ,然后成功测试 Scheme 属性解析 URI 以确保它是 HTTP。
但是,如果您要查找的 URI 是较大文本块的子字符串,则可以使用正则表达式。
Yes I would use Uri.TryCreate and then test the Scheme property of successfully parsed URI's to ensure it is HTTP.
However, if the URI's you were looking for are substrings of a larger block of text, regex is the way to go.
我会选择基于正则表达式的方法,你的方法对我来说看起来不错
I would go for the regex based approach and your approach looks fine to me
您可以使用 System.Uri 类中内置的解析验证 URL。这样做的好处是可以正确处理 Url 中包含的查询字符串,并且应该能够解析 .Net 可以用作 Url 的任何字符串。
使用 TryCreate 尝试解析每个字符串后,检查 Uti.Scheme 属性是否为 HTTP uri(否则文件系统路径也会通过过滤器)。
You can use the parsing built in to the System.Uri Class to validate the Urls. This has the benefit of correctly handling query strings included with the Url, and should be able to parse any string that .Net can use as a Url.
After using TryCreate to attempt parsing each string, check that the Uti.Scheme property is an HTTP uri (otherwise a filesystem path would also pass the filter).