如何用正则表达式替换URL中的主机名?已实现IP地址替换
替换URL中的主机名(基于C# Regex.Replace)
看起来你已经搞定了IP地址的替换,现在要处理主机名的替换对吧?没问题,咱们可以通过调整正则表达式来实现,核心是精准匹配URL中协议后面的主机名部分,同时保留其他内容(协议、端口、路径、参数等)。
先明确主机名的规则
合法的主机名(比如example.com、sub.domain.co.uk、my-server-123)遵循RFC 1123规范:
- 由字母、数字、连字符(
-)和点(.)组成 - 每个标签(点分隔的部分)不能以连字符开头或结尾,最长63个字符
方案1:保留原协议,只替换主机名
这个方案更灵活,不管原URL是http还是https,都能保留协议,只替换主机名:
// 正则说明: // (https?://) 捕获协议部分(http://或https://) // 后面的部分匹配符合规则的主机名 Regex hostnameRegex = new Regex(@"(https?://)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)", RegexOptions.Compiled); // 测试用例1:普通域名带路径参数 string test1 = "https://old-hostname.com/path/to/resource?param=123"; string result1 = hostnameRegex.Replace(test1, match => $"{match.Groups[1].Value}new-hostname.org"); Console.WriteLine(result1); // 输出:https://new-hostname.org/path/to/resource?param=123 // 测试用例2:带端口的主机名 string test2 = "http://my.server:8080/api/v1"; string result2 = hostnameRegex.Replace(test2, match => $"{match.Groups[1].Value}new.server.io"); Console.WriteLine(result2); // 输出:http://new.server.io:8080/api/v1 // 测试用例3:多级子域名 string test3 = "https://sub.domain.co.uk/"; string result3 = hostnameRegex.Replace(test3, match => $"{match.Groups[1].Value}new-sub.domain.io"); Console.WriteLine(result3); // 输出:https://new-sub.domain.io/
方案2:直接替换协议+主机名(适合固定新协议的场景)
如果你确定新URL要用固定的协议(比如统一换成https://),可以简化写法:
Regex hostnameRegex = new Regex(@"https?://[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*", RegexOptions.Compiled); string test = "http://old-server.com:9090/"; string result = hostnameRegex.Replace(test, "https://new-server.com"); Console.WriteLine(result); // 输出:https://new-server.com:9090/
注意事项
- 这个正则会自动在遇到端口号(
:开头)、路径斜杠(/)或者字符串结束时停止匹配,不会误替换路径里的内容 - 如果你的场景中还有其他特殊的主机名格式(比如包含下划线?不过下划线在标准主机名里不合法,通常是内部使用),可以调整正则的字符集,比如把
[a-zA-Z0-9]改成[a-zA-Z0-9_]
内容的提问来源于stack exchange,提问作者C. Dodds
相关产品推荐
相关产品推荐

