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