Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REGEX - Extract OU from Distinguished Name

I need to extract "OU" part from my Distinguished Name with REGEX.

For exemple :

"CN=DAVID Jean Louis (a),OU=Coiffeur,OU=France,DC=Paris,DC=France"

"CN=PROVOST Franck,OU=Coiffeur,OU=France,DC=Paris,DC=France"

"CN=SZHARCOFF Michel (AB),OU=Coiffeur_Inter,OU=France,DC=Paris,DC=France"

I need to have

"OU=Coiffeur,OU=France"  

"OU=Coiffeur,OU=France"

"OU=Coiffeur_Inter,OU=France"

I try "CN=SZHARCOFF Michel (AB),OU=Coiffeur_Inter,OU=France,DC=Paris,DC=France" -match "^CN=[\w-()]*[\w]*" But doesn't succeed

like image 482
P0werSh3ell Avatar asked Feb 04 '26 15:02

P0werSh3ell


1 Answers

You may match all the OU= + 1 or more non-comma substrings with \bOU=[^,]+ regex and then join them with ,:

$matches = [regex]::matches($s, '\bOU=[^,]+') | % { $_.value }
$res = $matches -join ','

Output for the first string:

OU=Coiffeur,OU=France

Pattern details

  • \b - a word boundary to only match OU as a whole word
  • OU= - a literal substring
  • [^,]+ - 1 or more (+) characters other than (as [^...] is a negated character class) a comma.

See the regex demo.

like image 57
Wiktor Stribiżew Avatar answered Feb 06 '26 05:02

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!