How can I write a Regular Expression to read the name in an LDAP path when the name contains a comma?

时间:2015-07-08 15:41:34

标签: regex ldap

The regular expression below works perfectly:

^CN=([a-zA-Z\\]+\s+[a-zA-Z\\]+)\,.*$

With this value:

CN=John Smith,OU=Staff,DC=internal,DC=net

and leaves me with:

John Smith

If the value contains a comma in the name it fails.

CN=John\, Smith,OU=Staff,DC=internal,DC=net

The comma in the common name is escaped in LDAP using a backslash \, so it doesn't cause the path to break.

How would my regex look so I obtain John Smith or even John\, Smith?

1 个答案:

答案 0 :(得分:1)

If the format is always 'CN=VAL,OU=VAL...' then you could use the ',OU=' as a marker for the group capture. It has the benefit of being explicit which makes it self-documenting:

/^CN=(.+?),OU=.+$/

var inputs = [
  'CN=John\, Smith,OU=Staff,DC=internal,DC=net',
  'CN=John Smith,OU=Staff,DC=internal,DC=net'
  ];

var regexp = /^CN=(.+?),OU=.+$/;

var matches = inputs.map(function(input) {
  return input.replace(regexp, '$1');
});

document.write('<pre>' + JSON.stringify(matches, null, 4) + '</pre>');