-2

How can I extract substring "Amy Java" from below string in C#?

CN=Amy Java,OU=Singapore,OU=Users,DC=domain,DC=com
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Zakir HC
  • 262
  • 2
  • 4
  • 18

4 Answers4

2

This works for me:

var amyJavaText =
    "CN=Amy Java,OU=Singapore,OU=Users,DC=domain,DC=com"
        .Split(',')
        .Select(x => x.Split('='))
        .ToLookup(x => x[0], x => x[1])["CN"]
        .First();
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
1

it's all you need.

string result = str.Split(',')[0].Split('=')[1];
Doruk
  • 884
  • 9
  • 25
0

In addition to more generic way, you can create a Dictionary (in case of unique values in String provided) or List of KeyValuePair (for current string example) as follow:

var str = "CN=Amy Java,OU=Singapore,OU=Users,DC=domain,DC=com";

var dict = str.Split(',').Select(s=> s.Split('=')).ToDictionary(a => a[0].Trim(), a => a[1].Trim()); //Only if Key are unique 
var kvp =  str.Split(',').Select(s=> s.Split('=')).Select(a=> new KeyValuePair<string,string>( a[0].Trim(), a[1].Trim()));

Then you can use another Linq to select the key required.

var requiredValue = kvp.Where(u=> u.Key == "CN").Value;

will give you required value.

Vishnu
  • 2,135
  • 2
  • 30
  • 51
0
private string[] FindKeyValue(string str, string key)
{
    return str.Split(",".ToCharArray())
        .Select(x => x.Split("=".ToCharArray()))
        .Where(x => x[0] == key).Select(x => x[1]).ToArray();
}

Assuming you want know the value of CN, OU, DC etc. The string you have, looks like a key value pair where "CN" is a key and "Amy Java" is a value. It seems that a key can be present multiple times in the string. Therefore you have more than one value for a key. Use it as follows:

var str1 = "CN=Amy Java,OU=Singapore,OU=Users,DC=domain,DC=com";
string[] valuesOfCN = FindKeyValue(str1, "CN");

If you want just a single value such as first value then use

var str1 = "CN=Amy Java,OU=Singapore,OU=Users,DC=domain,DC=com";
string firstValueOfCN = FindKeyValue(str1, "CN").First();
Amit Hasan
  • 1,430
  • 1
  • 15
  • 33