简体   繁体   English

使用Regex提取值 - C#

[英]Extracting values using Regex - C#

I'm not much familiar with Regular expressions. 我对正则表达式并不熟悉。 I've a string from which I need to extract specific values using regex. 我有一个字符串,我需要使用正则表达式提取特定值。 Here is the string 这是字符串

CN=ReportingGroup {b4f3d644-9361-461e-b604-709fa31f2b9e},OU=DOM USERS,DC=domain,DC=com

I want to get the values of CN and OU namely "ReportingGroup {b4f3d644-9361-461e-b604-709fa31f2b9e}" and "DOM USERS " 我想得到CN和OU的值,即“ReportingGroup {b4f3d644-9361-461e-b604-709fa31f2b9e}”和“DOM USERS”

from the above string. 从上面的字符串。 How can i construct the regex pattern for that? 我如何为此构建正则表达式模式?

You don't need a RegEx for this. 您不需要RegEx。

If you split the string using , and then each resulting string with = , you can look through the keys in order to extract the value for the CN and the OU keys. 如果使用分割字符串,然后使用=分隔每个结果字符串,则可以查看键以提取CNOU键的值。

string cn;
string ou;
foreach(string adPortion in myString.Split(new Char [] {','}))
{
   string[] kvp = adPortion.Split(new Char [] {'='})

   if(kvp[0] == "CN")
      cn = kvp[1];

   if(kvp[0] == "OU")
      ou = kvp[1];
}

This assumes that CN and OU only appear once in the string. 这假设CNOU仅在字符串中出现一次。

请执行下列操作:

new Regex("CN=(?<CN>[^,]*),OU=(?<OU>[^,]*)").Match(str).Groups["CN"].Value;

It looks like your string is pretty well structured. 看起来你的字符串结构很好。 Consider using regular string functions like IndexOf() and Substring() . 考虑使用常规字符串函数,如IndexOf()Substring() Regex are harder to read and understand. 正则表达式更难阅读和理解。

If you absolutely want to use Regex, the following code will iterate though all KEY=VALUE pairs: 如果您绝对想要使用Regex,以下代码将迭代所有KEY = VALUE对:

        foreach (Match m in
            Regex.Matches(inputString, @"[,]*([^=]+)=([^,]*)"))
        {
            string key = m.Groups[1].Value;
            string value = m.Groups[2].Value;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM