如何:从 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+)

匹配一个或多个单词字符。 将此组命名为 proto。

://

匹配冒号后跟两个左斜线的形式。

[^/]+?

匹配左斜线之外的任何字符的一个或多个匹配项(但要尽可能少)。

(?<port>:\d+)?

匹配零个或一个以冒号后跟一个或多个数字字符形式存在的匹配项。 将此组命名为 port。

/

匹配左斜线。

Match.Result 方法扩展 ${proto}${port} 替换序列,该序列用于连接在正则表达式模式中捕获的两个命名组的值。 它是显式串联从 Match.Groups 属性返回的集合对象中检索的字符串的一种简便的替代方法。

本示例使用带有两个替换项(${proto} 和 ${port})的 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 正则表达式