[英]Extract a substring from a string in C#
How can I extract the substring "John Woo" from the below string in C# 如何从C#中的下面的字符串中提取子字符串“John Woo”
CN=John Woo,OU=IT,OU=HO,DC=ABC,DC=com CN = John Woo,OU = IT,OU = HO,DC = ABC,DC = com
Thanks ! 谢谢 !
You could use a Lookup<TKey, TElement>
: 您可以使用
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). 请注意,如果密钥不存在(如在字典中),或者密钥不是uniqe(如在字典中),则既不会出现异常。 The value is a
IEnumerable<TElement>
. 该值是
IEnumerable<TElement>
。
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;
}
试试这个(这是一个非通用的答案):
var name = str.Split(',').Where(n => n.StartsWith("CN=")).FirstOrDefault().Substring(3);
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
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]
: 最后,值部分将是
nameValuePair[1]
:
var value = nameValuePair[1];
(No error handling shown above - you would of course have to add some.) (没有上面显示的错误处理 - 你当然必须添加一些。)
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 ",".
下面的代码适用于我想要提取的每个子字符串,它们落在“CN =”之后和第一次出现“,”之前。
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" 结果是“John Woo”
Thanks all for your help... 感谢你的帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.