我需要解析字符串,可以是下列条件之一:提取证书名称
"CN=bbb1, OU=b, O=b, L=b, S=b, C=US" //expected result bbb1
"CN=*.host.com, OU=b, O=b, L=b, S=b, C=US" //expected result *.host.com
"CN = *.host.com " //expected result *.host.com
"CN = bbb1 " //expected result bbb1
我写了下面的解析函数:
public static string GetCertificateName(string certSubject)
{
System.Text.RegularExpressions.Regex regex;
try
{
regex = new System.Text.RegularExpressions.Regex(@"CN\s*=\s*(?<name>\w+)");
var match = regex.Match(certSubject);
return match.Groups["name"].Value;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return "Can't parse";
}
static void Main(string[] args)
{
Console.WriteLine(GetCertificateName("CN=bbb1, OU=b, O=b, L=b, S=b, C=US")); //bbb1
Console.WriteLine(GetCertificateName("CN = bbb3 "));//bb33
Console.WriteLine(GetCertificateName("CN = bbb4\n\t "));//bbb4
Console.WriteLine(GetCertificateName("CN=*.host.com"));//empty string!!! != *.host.com
Console.ReadLine();
}
请帮我以提高我的解析功能,所以GetCertificateName(“CN = *。host.com”)调用将返回* .host.com 非常感谢, 娜塔莉
'请帮我improve'什么需要改进,到底是什么? – Abion47
'\ w +'不匹配'*'。将其更改为'\ S +'或'[\ w *] +',它应该可以工作。 –
选中此:https://regex101.com/r/LsTjYb/3 – MYGz