Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(PowerShell) split string with escaped separator characters

The split module is often used to split Active Directory Distinguished Names and Canonical Names to RDNs conveniently forgetting about the escaped separator characters that might be used in OUs and CNs as:

Distinguished Name Example with an escaped comma:

CN=Test User,OU=Comma\,Test,OU=Test,DC=domain,DC=com

Canonical Name Example with an escaped slash:

Domain.com/Test/Slash\/Test/Test User

There are several splitting examples on the internet that do not even mention this trap which might work for a long time but sooner or later will cause a lot of pain troubleshooting this programming flaw .

I don’t think there is an easy way to correctly split escaped strings using a Regular Expression (see also: Is there a pure regex split of a string containing escape sequences?). .

like image 453
iRon Avatar asked Jan 23 '26 22:01

iRon


1 Answers

Using negative lookbehind:

$text = 'CN=Test User,OU=Comma\,Test,OU=Test,DC=domain,DC=com'
$text -split '(?<!\\),'

CN=Test User
OU=Comma\,Test
OU=Test
DC=domain
DC=com

$text = 'Domain.com/Test/Slash\/Test/Test User'
$text -split '(?<!\\)/'

Domain.com
Test
Slash\/Test
Test User
like image 93
mjolinor Avatar answered Jan 25 '26 18:01

mjolinor



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!