4

I have the following string:

cn=abcd,cn=groups,dc=domain,dc=com

Can a regular expression be used here to extract the string after the first cn= and before the first ,? In the example above the answer should be abcd.

Brad Mace
  • 27,194
  • 17
  • 102
  • 148
Eddie Awad
  • 3,669
  • 1
  • 19
  • 17

5 Answers5

12
 /cn=([^,]+),/ 

most languages will extract the match as $1 or matches[1]

If you can't for some reason wield subscripts,

$x =~ s/^cn=//
$x =~ s/,.*$//

Thats a way to do it in 2 steps.

If you were parsing it out of a log with sed

sed -n -r '/cn=/s/^cn=([^,]+),.*$/\1/p'    < logfile > dumpfile 

will get you what you want. ( Extra commands added to only print matching lines )

Kent Fredric
  • 56,416
  • 14
  • 107
  • 150
7
/^cn=([^,]+),/
shelfoo
  • 1,569
  • 13
  • 15
2

Also, look for a pre-built LDAP parser.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

I had to work that out in PHP.

Since a LDAP string can sometimes be lengthy and have many attributes, I thought of contributing how I am using it in a project.

I wanted to use:

CN=username,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com

And turn it into:

array (
    [CN] => array( username )
    [OU] => array( UNITNAME, Region, Country )
    [DC] => array ( subdomain, domain, com )
)

Here is how I built my method.

/**
 * Read a LDAP DN, and return what is needed
 *
 * Takes care of the character escape and unescape
 *
 * Using:
 * CN=username,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com
 *
 * Would normally return:
 * Array (
 *     [count] => 9
 *     [0] => CN=username
 *     [1] => OU=UNITNAME
 *     [2] => OU=Region
 *     [5] => OU=Country
 *     [6] => DC=subdomain
 *     [7] => DC=domain
 *     [8] => DC=com
 * )
 *
 * Returns instead a manageable array:
 * array (
 *     [CN] => array( username )
 *     [OU] => array( UNITNAME, Region, Country )
 *     [DC] => array ( subdomain, domain, com )
 * )
 *
 *
 * @author gabriel at hrz dot uni-marburg dot de 05-Aug-2003 02:27 (part of the character replacement)
 * @author Renoir Boulanger
 * 
 * @param  string $dn          The DN
 * @return array
 */
function parseLdapDn($dn)
{
    $parsr=ldap_explode_dn($dn, 0);
    //$parsr[] = 'EE=Sôme Krazï string';
    //$parsr[] = 'AndBogusOne';
    $out = array();
    foreach($parsr as $key=>$value){
        if(FALSE !== strstr($value, '=')){
            list($prefix,$data) = explode("=",$value);
            $data=preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $data);
            if(isset($current_prefix) && $prefix == $current_prefix){
                $out[$prefix][] = $data;
            } else {
                $current_prefix = $prefix;
                $out[$prefix][] = $data;
            }
        }
    }
    return $out;
}
renoirb
  • 569
  • 5
  • 15
0

Yeah, using perl/java syntax cn=([^,]*),. You'd then get the 1st group.

sblundy
  • 60,628
  • 22
  • 121
  • 123