C# Regex Matches Method



The method matches instances of a pattern and is used to extract value based on a pattern.

Let us see hoe to check for a valid URL.

For that, pass the regex expression in the Matches method.

MatchCollection mc = Regex.Matches(text, expr);

Above, the expr is our expression that we have set to check for valid URL.

"^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?”

The text we have set to check is a URL i.e.

https://demo.com

Let us see the complete code.

Example

 Live Demo

using System;
using System.Text.RegularExpressions;
namespace Demo {
   class Program {
      private static void showMatch(string text, string expr) {
         MatchCollection mc = Regex.Matches(text, expr);
         foreach (Match m in mc) {
            Console.WriteLine(m);
         }
      }
      static void Main(string[] args) {
         string str = "https://demo.com";
         Console.WriteLine("Matching URL...");
         showMatch(str, @"^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?");
         Console.ReadKey();
      }
   }
}

Output

Matching URL...
https://demo.com
Updated on: 2020-06-23T08:16:49+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements