如果在C#中输入的内容如此有效或无效,如何验证URL [英] How to validate URL if valid or invalid if the entry is like this in C#

查看:88
本文介绍了如果在C#中输入的内容如此有效或无效,如何验证URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果条目如下有效或无效,如何验证URL:



www.com - 应无效

http ://ww.try.net - 应该是无效的

http://winner.com - 应该是有效的

url = null =应该是无效的







以下是我制作的方法,不能验证上述情况。



提前感谢您的帮助



我尝试过:



How to validate URL if valid or invalid if the entry is like this:

www.com - should be invalid
http://ww.try.net - should be invalid
http://winner.com - should be valid
url = null = should be invalid



Below is the method I made which does not validate the above scenario.

Thank you in advance for your kind help

What I have tried:





<pre> public bool IsUrlValid(string webUrl)
        {
            if (webUrl == null) return false;
            return Regex.IsMatch(webUrl, @"(http|https)://(([www\.])?|([\da-z-\.]+))\.([a-z\.]{2,3})$");
        }

推荐答案

);
}


无论正则表达式是什么,都有内置函数: Uri.IsWellFormedUriString Method( String,UriKind)(系统) [ ^ ]



例如:

No matter of regex pattern, there's inbuilt function: Uri.IsWellFormedUriString Method (String, UriKind) (System)[^]

Exmaple:
List<string> uris = new List<string>(){"www.com", "http://ww.try.net", "http://winner.com", "url = null"};

var result = uris.Select(x=> new {Uri = x, IsValid = Uri.IsWellFormedUriString(x, UriKind.Absolute)});

foreach(var u in result)
{
	Console.WriteLine("'{0}' is{1}valid", u.Uri, u.IsValid ? " ":" NOT ");
}



结果:


Result:

'www.com' is NOT valid
'http://ww.try.net' is valid
'http://winner.com' is valid
'url = null' is NOT valid





如果你想使用Regex,你可以使用它: ^ http(s)?://([\w-] +。)+ [\w - ] +(/ [\\\-。/?%& =])?



In case, you want to use Regex instead, you can use this: ^http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?



这篇关于如果在C#中输入的内容如此有效或无效,如何验证URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆