Regular Expression help

Michael M1
Giga Expert

I need to extract the user name from an AD attribute.

The string looks something like "CN=Rosana Smith,OU=Employees,..."

I wrote an expression of: var mike = str.match(/\b(\w)+ (\w)+/jg);

This works, except if I run into a name of Rosana Smith-Jones, it will not capture the third name. If I adjust to match against this then it doesn't work for non-hyphen names. Also, some people have 3 names "Billy Rae Cyrus".

My question is, how can I write an expression to capture all characters between (but not including) the CN= and the first comma (,) ?

1 ACCEPTED SOLUTION

Here is how you would get the name out of the string:

var myString = "CN=Rosana Smith,OU=Employees,..";
var myRegexp = /CN=(.*?),/g;
var match = myRegexp.exec(myString);
gs.print(match[1]);

The idea is you want to retrieve the first matching group and not the match itself.  Run it in a Background Script or in  Xplore: Developer Toolkit.

View solution in original post

8 REPLIES 8

If I enter your code as follows as a background script:

var str = ‘CN=Rosana Smith,OU=Employees,OU=Users,OU=Buenos_Aires,OU=Argentina,‘;

var mySubString = str.substring(str.lastIndexOf("=") +1, str.lastIndexOf(","));

gs.print(mySubString);

 

I get this output (which is incorrect) -  I need the person's name:

*** Script: Argentina

OK, your idea got my on the right path.

This works:

var mySubString = str.substring(str.indexOf("=") +1, str.indexOf(","));

 

Thanks!

Community Alums
Not applicable

glad that it worked. Please mark the correct answer whichever you think is useful, so the thread can be completed.

I would look at Jim's answer from a couple minutes ago, it is much better way to extract the string