I am new to the world of regex. I have a string that looks like this:
cn=foo,ou=bar,ou=zoo,ou=aa,ou=bb,ou=cc,ou=dd,o=someOrg,c=UK
. My goal is to extract foo, bar, and zoo
from it using JavaScript regex.
const dn = 'cn=foo,ou=bar,ou=zoo,ou=aa,ou=bb,ou=cc,ou=dd,o=someOrg,c=UK';
const regex = /^cn=(\w+),ou=(\w+),ou=(\w+)/;
const found = dn.match(regex);
console.log(found) --> Array ["cn=foo,ou=bar,ou=zoo", "foo", "bar", "zoo"]
Later on, the value of ou=bar
needs to be changed based on a new requirement to ou=bar - 1
, where the new value may contain a -
or a number
in any order within the string. I attempted to modify my regex pattern as follows:
const regex = /^cn=(\w+),ou=(.+),ou=(\w+)/;
Unfortunately, this regex returned unwanted data:
Array ["cn=foo,ou=bar,ou=zoo,ou=aa,ou=bb,ou=cc,ou=dd", "foo", "bar,ou=zoo,ou=aa,ou=bb,ou=cc", "dd"]
What I actually want is:
Array ["cn=foo,ou=bar - 1,ou=zoo", "foo", "bar - 1", "zoo"]
. I tried to exclude the unwanted data by using ^(ou=aa|ou=bb|ou=cc|ou=dd|o=someOrg|c=UK)
within the regex, but ended up with a null
value. Any help with correcting the regex syntax would be greatly appreciated.
Update:
I experimented with
/^cn=(\w+),ou=(\w+\s+-\s+\d+),ou=(\w+)/
which works for the previous example but doesn't cover cases like ou=bar-1
or ou=1bar-
...