在 .NET 中查找 URL?

发布于 2024-10-09 17:07:12 字数 184 浏览 10 评论 0原文

给定一个字符串列表,我有兴趣查找哪些是有效的 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 技术交流群。

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

发布评论

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

评论(3

束缚m 2024-10-16 17:07:12

是的,我会使用 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.

浸婚纱 2024-10-16 17:07:12

我会选择基于正则表达式的方法,你的方法对我来说看起来不错

I would go for the regex based approach and your approach looks fine to me

只涨不跌 2024-10-16 17:07:12

您可以使用 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).

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