Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to validate a URL using regular expression in C#?
To validate a URL using regular expressions in C#, you need to check for proper URL structure including protocols, domain names, and top-level domains. Regular expressions provide a powerful way to match URL patterns and ensure they conform to expected formats.
URL Components to Validate
A valid URL typically consists of the following components −
Protocol: http or https
Domain: The website name (e.g., example, google)
Top-level domain: .com, .org, .net, .edu, etc.
Optional path and query parameters: Additional URL components
Syntax
Following is the basic syntax for URL validation using regular expressions −
string pattern = @"^(https?://)?([\w-]+\.)+[\w-]{2,}(/.*)?$";
bool isValid = Regex.IsMatch(url, pattern);
A more comprehensive regex pattern for URL validation −
string pattern = @"^(https?://)?(www\.)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(/.*)?$";
Using Regex.IsMatch() for URL Validation
Example
using System;
using System.Text.RegularExpressions;
class URLValidator {
public static void Main(string[] args) {
string[] urls = {
"https://www.example.com",
"http://example.org",
"www.tutorialspoint.com",
"invalid-url",
"https://sub.domain.co.uk/path?param=value"
};
string pattern = @"^(https?://)?(www\.)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(/.*)?$";
Console.WriteLine("URL Validation Results:");
Console.WriteLine("Pattern: " + pattern);
Console.WriteLine();
foreach (string url in urls) {
bool isValid = Regex.IsMatch(url, pattern);
Console.WriteLine($"{url} - {(isValid ? "Valid" : "Invalid")}");
}
}
}
The output of the above code is −
URL Validation Results:
Pattern: ^(https?://)?(www\.)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(/.*)?$
https://www.example.com - Valid
http://example.org - Valid
www.tutorialspoint.com - Valid
invalid-url - Invalid
https://sub.domain.co.uk/path?param=value - Valid
Using Regex.Matches() for Detailed Analysis
Example
using System;
using System.Text.RegularExpressions;
class DetailedURLValidator {
private static void AnalyzeURL(string text, string pattern) {
Console.WriteLine($"Analyzing: {text}");
MatchCollection matches = Regex.Matches(text, pattern);
if (matches.Count > 0) {
foreach (Match match in matches) {
Console.WriteLine($"Match found: {match.Value}");
Console.WriteLine($"Position: {match.Index}");
Console.WriteLine($"Length: {match.Length}");
}
} else {
Console.WriteLine("No valid URL pattern found");
}
Console.WriteLine();
}
public static void Main(string[] args) {
string[] testStrings = {
"Visit https://www.tutorialspoint.com for tutorials",
"Check out http://example.org and https://test.com",
"Invalid text with no URLs"
};
string urlPattern = @"https?://(www\.)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(/[^\s]*)?";
foreach (string text in testStrings) {
AnalyzeURL(text, urlPattern);
}
}
}
The output of the above code is −
Analyzing: Visit https://www.tutorialspoint.com for tutorials Match found: https://www.tutorialspoint.com Position: 6 Length: 32 Analyzing: Check out http://example.org and https://test.com Match found: http://example.org Position: 10 Length: 18 Match found: https://test.com Position: 33 Length: 17 Analyzing: Invalid text with no URLs No valid URL pattern found
Creating a URL Validation Method
Example
using System;
using System.Text.RegularExpressions;
class URLValidationHelper {
public static bool IsValidURL(string url) {
if (string.IsNullOrWhiteSpace(url))
return false;
string pattern = @"^(https?://)?(www\.)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(/.*)?$";
return Regex.IsMatch(url, pattern, RegexOptions.IgnoreCase);
}
public static void ValidateAndDisplay(string url) {
bool isValid = IsValidURL(url);
Console.WriteLine($"URL: {url}");
Console.WriteLine($"Status: {(isValid ? "? Valid" : "? Invalid")}");
Console.WriteLine();
}
public static void Main(string[] args) {
string[] testURLs = {
"https://www.google.com",
"http://stackoverflow.com/questions",
"www.github.com",
"ftp://example.com",
"not-a-url",
"https://sub.domain.co.uk/path/to/page?query=value#anchor"
};
Console.WriteLine("URL Validation Test Results:");
Console.WriteLine("============================");
foreach (string url in testURLs) {
ValidateAndDisplay(url);
}
}
}
The output of the above code is −
URL Validation Test Results: ============================ URL: https://www.google.com Status: ? Valid URL: http://stackoverflow.com/questions Status: ? Valid URL: www.github.com Status: ? Valid URL: ftp://example.com Status: ? Invalid URL: not-a-url Status: ? Invalid URL: https://sub.domain.co.uk/path/to/page?query=value#anchor Status: ? Valid
Common URL Validation Patterns
| Pattern Type | Regular Expression | Description |
|---|---|---|
| Basic HTTP/HTTPS | ^https?://[^\s]+$ |
Matches URLs starting with http:// or https:// |
| With Optional Protocol | ^(https?://)?[\w\.-]+\.\w+$ |
Protocol is optional, domain required |
| Comprehensive | ^(https?://)?(www\.)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(/.*)?$ |
Includes subdomains, paths, and parameters |
Conclusion
Regular expressions provide an effective way to validate URL formats in C#. The Regex.IsMatch() method is ideal for simple validation, while Regex.Matches() offers detailed analysis. Choose the appropriate regex pattern based on your specific validation requirements and URL format complexity.
