下面的示例从 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 属性返回的集合对象检索到的字符串。
此示例使用有两处替换(${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)