在 c# 中使用正则表达式提取证书名称



我需要解析一个字符串,该字符串可以是以下字符串之一:

"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(@"CNs*=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 =  bbb4nt "));//bbb4
    Console.WriteLine(GetCertificateName("CN=*.host.com"));//empty string!!! != *.host.com
    Console.ReadLine( );
}

请帮助我改进我的解析功能,以便 GetCertificateName("CN=*.host.com") 调用将返回 *.host.com多谢娜塔莉

如果

CN在字符串的开头(正如我们在所有示例中所看到的),您可以尝试Linq解决方案(从=开始,在,处停止,修剪中间)

  string source = "CN  = *.host.com ";
  string result = string.Concat(source
      .SkipWhile(c => c != '=')
      .Skip(1)
      .TakeWhile(c => c != ','))
    .Trim();

甚至是老IndexOfSubstring

  string source = "CN  =*.host.com,";
  int start = source.IndexOf('=') + 1;
  int stop = start <= 0 ? - 1 : source.IndexOf(',', start);
  string result = start <= 0 ? null 
    : stop >= 0 ? source.Substring(start, stop - start).Trim()
    : source.Substring(start).Trim();

我的解决方案:)

public static string GetCertificateName(string certSubject)
{
    //"CN=bbb1, OU=b, O=b, L=b, S=b, C=US"  
    System.Text.RegularExpressions.Regex regex;
    try
    {
        regex = new System.Text.RegularExpressions.Regex(@"CNs*=s*(?<name>*?.?w*.?w+)");
        var match = regex.Match(certSubject);
        return match.Groups["name"].Value;
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return "Can't parse";
} 

不使用正则表达式的附加答案:

  public static string Parsing(string certSubject)
    {
        string[] strArr = certSubject.Split(new char[] { '=', ' ', 't', 'n',',' });
    string subject = "";
    for (int i = 0; i < strArr.Length; i++)
    {
        if (strArr[i].Equals("cn", StringComparison.InvariantCultureIgnoreCase))
        {
            if ((i + 1) < strArr.Length)
            {
                subject = strArr[i + 1];
                break;
            }
        }
    }
    if (subject.Length > 0)
    {
        return subject;
    }
    return "Can't parse";
}

相关内容

  • 没有找到相关文章

最新更新