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 "
from the above string. How can i construct the regex pattern for that?
You don't need a RegEx for this.
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.
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.
Do the following:
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()
. Regex are harder to read and understand.
If you absolutely want to use Regex, the following code will iterate though all KEY=VALUE pairs:
foreach (Match m in
Regex.Matches(inputString, @"[,]*([^=]+)=([^,]*)"))
{
string key = m.Groups[1].Value;
string value = m.Groups[2].Value;
}
精彩评论