This has been asked before here, but the answers are all PHP related. Is there a similar and working solution using C#? Like a specific test class or routine? I want to parse www.google.com or google.com or mywebsite.net etc... with or without prefixes. Thanks
Asked
Active
Viewed 2.4k times
3 Answers
23
C# has Regex as well, but this seems simpler:
bool isUri = Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute);
(Answered at Regular expression for URL)

Community
- 1
- 1

user2357661
- 262
- 2
- 2
-
1This worked for me. The Uri.TryCreate() methods mentioned always returned NULL because the url I am pasrsing is simply something like "www.google.com". It may or may not contain HTTP or HTTPS or FTP, etc – Fandango68 Mar 19 '15 at 05:25
-
For me does not work. I've tested "www.google.com" and will pass, next I've tested "w" and pass the same. It will does not check correctly. – Marco Concas May 14 '19 at 10:08
-
@MarcoConcas has it right - something as simple as "bob" will pass right through this methodology and be called a valid uri... which it most certainly isn't. – PKD Jun 17 '22 at 00:09
3
https://msdn.microsoft.com/en-us/library/system.web.webpages.validator.regex(v=vs.111).aspx
you use the above mentioned class or use the below regex and check Regex matches with your url string
Regex UrlMatch = new Regex(@"(?i)(http(s)?:\/\/)?(\w{2,25}\.)+\w{3}([a-z0-9\-?=$-_.+!*()]+)(?i)", RegexOptions.Singleline);
Regex UrlMatchOnlyHttps = new Regex(@"(?i)(http(s)?:\/\/)(\w{2,25}\.)+\w{3}([a-z0-9\-?=$-_.+!*()]+)(?i)", RegexOptions.Singleline);
you can also use the above regexpattern to validate the url

balaji dileep kumar
- 622
- 7
- 12
1
You can use this way:
bool result = Uri.TryCreate(uriName, UriKind.RelativeOrAbsolute, out uriResult)
&& uriResult.Scheme == Uri.UriSchemeHttp;

Santosh Panda
- 7,235
- 8
- 43
- 56
-
What about HTTPS and what if I don't have those prefixes? I want to check www.google.com for example or even google.com – Fandango68 Mar 19 '15 at 05:26