I'm trying to look for users inside Active Directory through a LDAP query. Basically I'm searching for the user in this way:

Search DN: dc=mydomain, dc=com
Filter: (sAMAccountName=USER)  where USER is replaced with the provided username.

Now if USER is only the username without domain (for ex. "Joe") this works fine. However I receive them in the form (domain\username, for ex. "myDomain\Joe") and obviously the search fails.

I see two ways:

  • using a regex inside the Search Filter to discard the domain
  • using a completely different search filter

I'm no LDAP expert and I don't even know if it's possible to use regular expressions inside the search filters.

Does anyone know if it's possible and how?

P.S. I cannot pre-process the username to strip the domain. This cannot be changed, as it's all part of a large system.

  • 2
    what tool are you using for ldap queries? – Jim B May 20 '10 at 10:46

It is not possible to use different filter. User account hasn't attribute with domain name, so you cannot construct query with domain as parameter.

In Active Directory LDAP service contains only information from domain, for which DC is controller. If you have trusts with other domianst in forest, for getting information abount user from different domain you should contact with LDAP service from that domain.

Proper solution: discard domain name from search filter. Attribute sAMAccountName is unique in domain.


If you are on a *nix box, use openldap utilities and the search is simple. Example

ldapsearch -h servername -b "dc=domain,dc=com" -D bindid@domain.com -W -x sAMAccountName=username

userPrincipalName: username@domain.com

I am not sure if you can use regex inside the filter. Write a script that dumps the output to a file and implement regex.


LDAP supports wildcards, but I don't know about regex (it's possible that some specific implementations might)

You could use the following filter:


Which would match either the username, or some characters, backslash, and the username.

Depending on what tool you're using will affect how or if you'll need to escape the backslash.


The Pre-Win2k domain name is not part of the sAMAccountName attribute. If you want to search for domain in the username... use userPrincipleName which is the format username@domainFQDN Ex: joe.smith@corp.com

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.