當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# Regex.Matches用法及代碼示例

該方法匹配模式的實例,用於根據模式提取值。

讓我們看看 hoe 來檢查一個有效的 URL。

為此,在 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

相關用法


注:本文由純淨天空篩選整理自Samual Sam大神的英文原創作品 C# Regex. Matches Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。