Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to validate a URL using regular expression in C#?
To validate, you need to check for the protocols.
http https
With that, you need to check for .com, .in, .org, etc.
For this, use the following regular expression −
(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?
The following is the code −
Example
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
class Program {
private static void showMatch(string text, string expr) {
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc) {
Console.WriteLine(m);
}
}
static void Main(string[] args) {
string str = "https://example.com";
Console.WriteLine("Matching URL...");
showMatch(str, @"^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?");
Console.ReadKey();
}
}
}
Output
Matching URL... The Expression: ^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)? https://example.com
Advertisements