- 1 year ago
REGEX - Extract OU from Distinguished Name
Comment
1 / 1
To extract the Organizational Unit (OU) from a Distinguished Name (DN) using regular expressions, you can use the following pattern:
rubyOU=(.*?)(?:,|$)
Explanation of the pattern:
OU=
: Matches the "OU=" string literally, which is the prefix for Organizational Units in Distinguished Names.(.*?)
: Captures the OU value using a non-greedy match. The.*?
matches any characters (except newline) lazily until the first occurrence of the next part of the pattern.(?:,|$)
: This is a non-capturing group that matches either a comma (,
), which separates different parts of the DN, or the end of the string ($
). It ensures that the regex stops capturing the OU value when it reaches the end of the OU field.
Here's an example of how you can use the regex in Python to extract the OU from a Distinguished Name:
pythonimport re
dn = "CN=John Doe,OU=Users,OU=Company,DC=example,DC=com"
# Define the regex pattern
pattern = r"OU=(.*?)(?:,|$)"
# Use re.search to find the match
match = re.search(pattern, dn)
# Check if the match was found and extract the OU value
if match:
ou = match.group(1)
print("OU:", ou)
else:
print("OU not found in Distinguished Name.")
Output:
makefileOU: Users
This code will extract the value of the first OU from the Distinguished Name. If there are multiple OUs in the DN, you can use re.findall()
instead of re.search()
to extract all occurrences of OUs.