5

I want to extract the string after the last occurrence of "cn=" using regex in C# application. So what I need is the string between last occurence of "cn=" and \ character Please note that the source string may contains spaces.

Example:

ou=company\ou=country\ou=site\cn=office\cn=name\ou=pet

Result:

name

So far Ive got (?<=cn=).* for selecting the text after the cn= using positive lookbehind and (?:.(?!cn=))+$ for finding the last occurence but I dont know how to combine it together to get desired result.

pandemic
  • 1,135
  • 1
  • 22
  • 39

3 Answers3

4

You may try using the following regex ...

(?m)(?<=cn=)[\w\s]+(?=\\?(?:ou=)?[\w\s]*$)

see regex demo

C# ( demo )

using System;
using System.Text.RegularExpressions;

public class RegEx
{
    public static void Main()
    {
        string pattern = @"(?m)(?<=cn=)[\w\s]+(?=\\?(?:ou=)?[\w\s]*$)";
        string input = @"ou=company\ou=country\ou=site\cn=office\cn=name\ou=pet";

        foreach (Match m in Regex.Matches(input, pattern))
        {
            Console.WriteLine("{0}", m.Value);
        }
    }
}
m87
  • 4,445
  • 3
  • 16
  • 31
  • the last occurence of cn=whatever may or may not be followed by another subcontainers(\ou=whatever\). tried to remove the ou with escaped \ only but got a string "office instead" – pandemic Mar 19 '17 at 04:35
2

You could use a negative lookahead:

cn=(?!.*cn=)([^\\]+)

Take group $1 and see a demo on regex101.com. As full C# code, see a demo on ideone.com.


To only have one group, add another lookaround:
(?<=cn=)(?!.*cn=)([^\\]+)
Jan
  • 42,290
  • 8
  • 54
  • 79
  • can you please modify the regex to have it matched but selects the value without the "cn="? the match itself is working flawlessly @Jan – pandemic Mar 19 '17 at 09:50
  • @pandemic: Just use another lookaround: https://regex101.com/r/GDZJDS/2, updated the answer. – Jan Mar 19 '17 at 10:05
2

Another idea by just using a capturing group for getting the desired part.

string pattern = @"^.*cn=(\w+)";

The extracted match will be in m.Groups[1] (see demo).

Community
  • 1
  • 1
bobble bubble
  • 16,888
  • 3
  • 27
  • 46