如何更改 C# 函数中的以下正则表达式以获得如下所示的结果?由于语言代码总数是固定的,我可以只修改 RegEx 模式而不是 C# 代码吗?谢谢。
C# 函数:
public static string GetSubdomain(string url)
{
string pat = @"^https://www\.(.*?)/(english|german|italian)/.*$";
string rep = @"http://$2.$1/";
return Regex.Replace(url, pat, rep);
}
结果:
http://www.example.org/english/ => http://en.example.org/
http://www.example.org/german/ => http://de.example.org/
http://www.example.org/italian/ => http://it.example.org/
最佳答案
您可以使用语言名称和代码的字典并使用以下解决方案:
var dct = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
{ "english", "en"},
{ "german", "de"},
{ "italian", "it" }
};
//var url = "http://www.example.org/english/"; // http://en.example.org/
var url = "https://www.example.org/german/"; // https://de.example.org/
string pat = @"(?i)^(https?://)www\.(.*?)/(english|german|italian)/.*$";
Console.WriteLine(Regex.Replace(url, pat, m => {
var val = "";
return dct.TryGetValue(m.Groups[3].Value, out val) ?
$"{m.Groups[1].Value}{dct[m.Groups[3].Value]}.{m.Groups[2].Value}/" :
$"{m.Groups[1].Value}{m.Groups[3].Value}.{m.Groups[2].Value}/";
}
)
);
请参阅C# demo .
模式匹配
(?i)
- 使正则表达式不区分大小写^
- 字符串开头(https?://)
- 第 1 组:http://
或https://
www\.
-www.
(用(?:...)?
括起来以选择性匹配)(.*?)
- 第 2 组:任意 0 个以上字符,尽可能少/
- 一个/
(英语|德语|意大利语)
- 第 3 组:3 个选项中的任何一个/
- 一个/
.*
- 该行的其余部分$
- 字符串结尾。
匹配后,dct.TryGetValue(m.Groups[3].Value, out val) ?
检查第 3 组值是否可以映射到语言代码,如果可以,dct[m.Groups[3].Value]
用于替换。否则,m.Groups[3].Value
按原样使用。
关于c# - .NET RegEx 用于替换 URL 中的语言代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51476508/