3

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

P0werSh3ell
  • 103
  • 1
  • 6

2 Answers2

4

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thanks ! I understand but is it possible to join 2 OU with 1 regex ? – P0werSh3ell Aug 09 '18 at 08:40
  • @P0werSh3ell Regex does not join texts, it only matches parts of/full strings that match the pattern. It is not possible to match discontinuous texts within one match operation. Thus, you either use multiple matching and then joining, or you may also get it using a single replace operation. The replacing approach is usually more cumbersome than matching and joining. – Wiktor Stribiżew Aug 09 '18 at 08:45
1

This pattern will support DistinguishedName properties containing commas, and provides named groups for matches. I use this in PowerShell to parse an ADObject's parent DN, etc.

^(?:(?<cn>CN=(?<name>.*?)),)?(?<parent>(?:(?<path>(?:CN|OU).*?),)?(?<domain>(?:DC=.*)+))$

See Regexr demo: https://regexr.com/5bt64

Kit
  • 61
  • 1
  • 2