Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace _02_ValidateURL_Regex
- {
- using System;
- using System.Text.RegularExpressions;
- class Startup
- {
- static void Main()
- {
- 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+)*)?$";
- Regex regex = new Regex(urlPattern);
- string url = Console.ReadLine();
- Match match = regex.Match(url);
- if (!match.Success)
- {
- Console.WriteLine("Invalid URL!");
- return;
- }
- string protocol = match.Groups["protocol"].ToString();
- string host = match.Groups["host"].ToString();
- string port = match.Groups["port"].ToString();
- string path = match.Groups["path"].ToString();
- string query = match.Groups["query"].ToString();
- string fragment = match.Groups["fragment"].ToString();
- if (string.IsNullOrEmpty(port))
- {
- if (protocol == "http")
- {
- port = "80";
- }
- else
- {
- port = "443";
- }
- }
- if (string.IsNullOrEmpty(path))
- {
- path = "/";
- }
- Console.WriteLine("Protocol: {0}", protocol);
- Console.WriteLine("Host: {0}", host);
- Console.WriteLine("Port: {0}", port);
- Console.WriteLine("Path: {0}", path);
- if (!string.IsNullOrEmpty(query))
- {
- Console.WriteLine("Query: {0}", query);
- }
- if (!string.IsNullOrEmpty(fragment))
- {
- Console.WriteLine("Fragment: {0}", fragment);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement