下列範例會從 URL 中擷取通訊協定和通訊埠編號。
範例
此範例會使用 Match.Result 方法來傳回通訊協定和通訊埠編號 (中間以冒號隔開)。
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim url As String = "https://www.contoso.com:8080/letters/readme.html"
Dim r As New Regex("^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/")
Dim m As Match = r.Match(url)
If m.Success Then
Console.WriteLine(r.Match(url).Result("${proto}${port}"))
End If
End Sub
End Module
' The example displays the following output:
' http:8080
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string url = "https://www.contoso.com:8080/letters/readme.html";
Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/");
Match m = r.Match(url);
if (m.Success)
Console.WriteLine(r.Match(url).Result("${proto}${port}"));
}
}
// 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);