Advertisement
Guest User

UrlValidator

a guest
May 22nd, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.21 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.             while (true)
  14.             {
  15.                 Regex regex = new Regex(urlPattern);
  16.  
  17.                 string url = WebUtility.UrlDecode(Console.ReadLine());
  18.  
  19.                 Match match = regex.Match(url);
  20.  
  21.                 if (!match.Success)
  22.                 {
  23.                     Console.WriteLine("Invalid URL!");
  24.                     continue;
  25.                 }
  26.  
  27.                 string protocol = match.Groups["protocol"].ToString();
  28.                 string host = match.Groups["host"].ToString();
  29.                 string port = match.Groups["port"].ToString();
  30.                 string path = match.Groups["path"].ToString();
  31.                 string query = match.Groups["query"].ToString();
  32.                 string fragment = match.Groups["fragment"].ToString();
  33.  
  34.                 if (string.IsNullOrEmpty(port))
  35.                 {
  36.                     if (protocol == "http")
  37.                     {
  38.                         port = "80";
  39.                     }
  40.                     else
  41.                     {
  42.                         port = "443";
  43.                     }
  44.                 }
  45.  
  46.                 if (string.IsNullOrEmpty(path))
  47.                 {
  48.                     path = "/";
  49.                 }
  50.  
  51.                 Console.WriteLine("Protocol: {0}", protocol);
  52.                 Console.WriteLine("Host: {0}", host);
  53.                 Console.WriteLine("Port: {0}", port);
  54.                 Console.WriteLine("Path: {0}", path);
  55.  
  56.                 if (!string.IsNullOrEmpty(query))
  57.                 {
  58.                     Console.WriteLine("Query: {0}", query);
  59.                 }
  60.  
  61.                 if (!string.IsNullOrEmpty(fragment))
  62.                 {
  63.                     Console.WriteLine("Fragment: {0}", fragment);
  64.                 }
  65.             }
  66.            
  67.         }
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement