Zakir HC
Zakir HC

Reputation: 302

Extract a substring from a string in C#

How can I extract the substring "John Woo" from the below string in C#

CN=John Woo,OU=IT,OU=HO,DC=ABC,DC=com

Thanks !

Upvotes: 2

Views: 5389

Answers (6)

Zakir HC
Zakir HC

Reputation: 302

I created the below code of my own and finally got the substring I needed. The below code works for every substring that I want to extract that falls after "CN=" and before first occurrence of ",".

string name = "CN=John Woo,OU=IT,OU=HO,DC=ABC,DC=com";
int index1 = name.IndexOf("=") + 1;
int index2 = name.IndexOf(",") - 3;
string managerName = name.Substring(index1, index2);

The Result was "John Woo"

Thanks all for your help...

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460028

You could use a Lookup<TKey, TElement>:

string text = "CN=John Woo,OU=IT,OU=HO,DC=ABC,DC=com";
var keyValues = text.Split(',')
    .Select(s => s.Split('='))
    .ToLookup(kv => kv[0], kv => kv.Last());
string cn = keyValues["CN"].FirstOrDefault();  // John Woo
// or, if multiple values with the same key are allowed (as suggested in the given string)
string dc = string.Join(",", keyValues["DC"]); // ABC,com

Note that you neither get an exception if the key is not present(as in a dictionary) nor if the key is not uniqe (as in a dictionary). The value is a IEnumerable<TElement>.

Upvotes: 5

Alessandro D&#39;Andria
Alessandro D&#39;Andria

Reputation: 8868

Something like this

var s = "CN=John Woo,OU=IT,OU=HO,DC=ABC,DC=com";
// this give you a enumarable of anonymous key/value
var v = s.Split(',') 
         .Select(x => x.Split('='))
         .Select(x => new
                      {
                          key = x[0],
                          value = x[1],
                      });
var name = v.First().value; // John Woo

Upvotes: 1

Matthew Watson
Matthew Watson

Reputation: 109537

You can firstly split the string by the commas to get an array of strings, each of which is a name/value pair separated by =:

string input = "CN=John Woo,OU=IT,OU=HO,DC=ABC,DC=com";
var nameValuePairs = input.Split(new[] {','});

Then you can split the first name/value pair like so:

var nameValuePair = nameValuePairs[0].Split(new[]{'='});

Finally, the value part will be nameValuePair[1]:

var value = nameValuePair[1];

(No error handling shown above - you would of course have to add some.)

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

Try this

var regex = new Regex("CN=(?<mygroup>.*?),");
var match = regex.Match("CN=John Woo,OU=IT,OU=HO,DC=ABC,DC=com");
if(match.Success)
{
    string result = match.Groups["mygroup"].Value;
}

Upvotes: 2

AlexH
AlexH

Reputation: 2700

Try this (this is a non generic answer) :

var name = str.Split(',').Where(n => n.StartsWith("CN=")).FirstOrDefault().Substring(3);

Upvotes: 1

Related Questions