เมธอดนี้จับคู่อินสแตนซ์ของรูปแบบ (pattern) และใช้สำหรับแยกค่าตามรูปแบบ
มาดูวิธีตรวจสอบ URL ที่ถูกต้อง
สำหรับนั้น ให้ส่งนิพจน์ regex ไปในเมธอด Matches:
MatchCollection mc = Regex.Matches(text, expr);
ข้างต้น expr คือนิพจน์ที่เรากำหนดเพื่อตรวจสอบ URL ที่ถูกต้อง:
"^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?"
ข้อความที่เรากำหนดให้ตรวจสอบคือ URL เช่น:
https://demo.com
มาดูโค้ดทั้งหมดกัน
ตัวอย่าง
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();
}
}
}
ผลลัพธ์
Matching URL...
https://demo.com