Quantcast
Viewing all articles
Browse latest Browse all 35

Answer by user2023861 for A more efficient way of extracting a name from a string?

Here's a simple Regex to pull out the CN value:

CN=([^,]*),

You can use this C# code to get the value:

string CN = Regex.Replace(input, @"CN=([^,]*),", "$1");

Here are the important points:

  • I'm assuming you want everything between the "CN=" and the next comma.
  • The Regex replace allows a special string in the last parameter. The "$1" will be replaced with all of the characters in between the parentheses.
  • You can test out the Regex here https://regex101.com/r/dT8lP8/1

In terms of computational efficiency, your solution is most likely more efficient than this Regex solution. You might see an improvement if you replace the second through fifth lines of your solution with this:

var StartIndex = Manager.IndexOf("=") + 1;var EndIndex = Manager.IndexOf(",", StartIndex) - 1;

I'm using this overload of the IndexOf method that tells the code at what index to start looking for the comma. This starts the search at index 3 ("J") instead of index 0 ("C"). Again, this might run a little faster, but probably not measurably so.


Viewing all articles
Browse latest Browse all 35

Trending Articles