我需要解析字符串,可以是下列條件之一:提取證書名稱
"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