如何:從 URL 擷取通訊協定和通訊埠編號

下列範例會從 URL 擷取通訊協定和連接埠號碼。

警告

使用 System.Text.RegularExpressions 來處理不受信任的輸入時,請傳遞逾時。 惡意使用者可以提供輸入給 RegularExpressions,導致拒絕服務的攻擊。 使用 RegularExpressions 的 ASP.NET Core 架構 API 會傳遞逾時。

範例

此範例會使用 Match.Result 方法來傳回通訊協定和連接埠號碼 (中間以冒號隔開)。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string url = "http://www.contoso.com:8080/letters/readme.html";

      Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/",
                          RegexOptions.None, TimeSpan.FromMilliseconds(150));
      Match m = r.Match(url);
      if (m.Success)
         Console.WriteLine(m.Result("${proto}${port}"));
   }
}
// The example displays the following output:
//       http:8080
Imports System.Text.RegularExpressions

Module Example
    Public Sub Main()
        Dim url As String = "http://www.contoso.com:8080/letters/readme.html"
        Dim r As New Regex("^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/",
                           RegexOptions.None, TimeSpan.FromMilliseconds(150))

        Dim m As Match = r.Match(url)
        If m.Success Then
            Console.WriteLine(m.Result("${proto}${port}"))
        End If
    End Sub
End Module
' The example displays the following output:
'       http:8080

規則運算式模式 ^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/ 的解譯方式如下表所示。

模式 描述
^ 在字串開頭開始比對。
(?<proto>\w+) 比對一個或多個文字字元。 將這個群組命名為 proto
:// 比對冒號加兩個斜線符號。
[^/]+? 比對一個或多個 (但越少越好) 出現的任何字元,但不包括斜線符號。
(?<port>:\d+)? 比對零個或一個出現的冒號外加一個或多個數字字元。 將這個群組命名為 port
/ 比對斜線符號。

Match.Result 方法會展開 ${proto}${port} 取代序列,以將規則運算式模式中所擷取之兩個具名群組的值串連在一起。 另一種方便的作法是將 Match.Groups 屬性所傳回之集合物件中擷取的字串明確地串連在一起。

此範例會使用 Match.Result 方法搭配兩個替代項目 ${proto}${port},以便在輸出字串中包含擷取的群組。 您可以改為從相符項目的 GroupCollection 物件中擷取該群組,如下列程式碼所示。

Console.WriteLine(m.Groups["proto"].Value + m.Groups["port"].Value);
Console.WriteLine(m.Groups("proto").Value + m.Groups("port").Value)

另請參閱