次の方法で共有


方法 : URL からプロトコルとポート番号を抽出する

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+)

1 つ以上の単語文字に一致します。 このグループに proto という名前を付けます。

://

コロンとそれに続く 2 つのスラッシュ記号に一致します。

[^/]+?

スラッシュ記号以外の任意の文字の 1 回以上の出現 (ただし、可能な限り少ない回数) に一致します。

(?<port>:\d+)?

コロンとそれに続く 1 つ以上の 10 進数字の 0 回以上の出現に一致します。 このグループに port という名前を付けます。

/

スラッシュ記号に一致します。

Match.Result メソッドは、正規表現パターンでキャプチャされた 2 つの名前付きグループを連結する ${proto}${port} 置換シーケンスを展開します。 これは、Match.Groups プロパティによって返されたコレクション オブジェクトから取得された文字列を明示的に連結する便利な代替方法です。

例では、${proto} と ${port} の 2 つの置換がある Match.Result メソッドを使用して、キャプチャされたグループを出力文字列に含めています。 次のコードに示すように、一致部分の GroupCollection オブジェクトから、キャプチャされたグループを取得できます。

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

参照

その他の技術情報

.NET Framework の正規表現