Advertisement
Guest User

UrlValidator

a guest
May 22nd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.98 KB | None | 0 0
  1. namespace _02_ValidateURL_Regex
  2. {
  3.     using System;
  4.     using System.Net;
  5.     using System.Text.RegularExpressions;
  6.  
  7.     class Startup
  8.     {
  9.         static void Main()
  10.         {
  11.             string urlPattern = @"^(?<protocol>(?<http>http)|https):\/\/(?<host>[\w-]+\.[a-z]{2,4})(?::(?<port>(?(http)(80|8080)|(443))))?(?<path>(\/[\w\d]*)*)?((?<!\/).[a-z]+)?(?:\?(?<query>(?:\b\w+=\w+&?)*))?(?:#(?<fragment>\w+)*)?$";
  12.  
  13.             Regex regex = new Regex(urlPattern);
  14.  
  15.             string url = WebUtility.UrlDecode(Console.ReadLine());
  16.  
  17.             Match match = regex.Match(url);
  18.  
  19.             if (!match.Success)
  20.             {
  21.                 Console.WriteLine("Invalid URL!");
  22.                 return;
  23.             }
  24.  
  25.             string protocol = match.Groups["protocol"].ToString();
  26.             string host = match.Groups["host"].ToString();
  27.             string port = match.Groups["port"].ToString();
  28.             string path = match.Groups["path"].ToString();
  29.             string query = match.Groups["query"].ToString();
  30.             string fragment = match.Groups["fragment"].ToString();
  31.  
  32.             if (string.IsNullOrEmpty(port))
  33.             {
  34.                 if (protocol == "http")
  35.                 {
  36.                     port = "80";
  37.                 }
  38.                 else
  39.                 {
  40.                     port = "443";
  41.                 }
  42.             }
  43.  
  44.             if (string.IsNullOrEmpty(path))
  45.             {
  46.                 path = "/";
  47.             }
  48.  
  49.             Console.WriteLine("Protocol: {0}", protocol);
  50.             Console.WriteLine("Host: {0}", host);
  51.             Console.WriteLine("Port: {0}", port);
  52.             Console.WriteLine("Path: {0}", path);
  53.  
  54.             if (!string.IsNullOrEmpty(query))
  55.             {
  56.                 Console.WriteLine("Query: {0}", query);
  57.             }
  58.  
  59.             if (!string.IsNullOrEmpty(fragment))
  60.             {
  61.                 Console.WriteLine("Fragment: {0}", fragment);
  62.             }
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement