Saturday, June 09, 2007

Using Regular Expressions in PeopleCode

Where are the PeopleCode Regular Expressions? They don't exist. Fortunately, since PeopleCode supports Java, we can "borrow" them for use in our PeopleCode. Here is an example similar to the BSF example I posted earlier:

Function get_site_name() Returns string
Local JavaObject &patternClass = GetJavaClass("java.util.regex.Pattern");
Local JavaObject &pattern = &patternClass.compile("/??(\w+?)(?:_\d+?)?/.+$");
Local JavaObject &jstring = CreateJavaObject("java.lang.String", %Request.PathInfo);
Local JavaObject &matches = &pattern.matcher(&jstring.subSequence(0, &jstring.length()));

If (&matches.matches()) Then
Return &matches.group(1);
Else
Return "";
End-If;
End-Function;

4 comments:

Jim Marion said...

Hmmm... It looks like I was a little late to the party on this one. ChiliJoe posted a good article on Java regular expressions a year and a half ago: Bringing the power of Regular Expressions to PeopleCode. Likewise, Chris Heller posted an example that uses regular expressions in PeopleCode about a year ago: Application Engine Development Tips

Kevin Weaver said...

What resources to you recommend for learning regex? Every time I have used them in the past I have copied someone's working example. Today I spend entirely too long trying to figure out how to exclude out the underscore window from the site name on a URL only to realize I don't understand Regex as well as I thought. The example I was using is from http://peoplesoft.wikidot.com/opening-a-new-window, and it works well if you are on the initial log in window, but does not work if you have opened a new window. Any thought on how I could improve this to take in account the "_number" on the site name?

Thanks,

Kevin Weaver

Jim Marion said...

@Kevin, I don't have a good place to learn regular expressions. I usually look up a regex reference and then put the pieces together.

It has been a long time since I wrote the regex above, but if I'm reading it correctly, it extracts the site name from the site_nn regardless of whether the _nn part exists. It looks like the PeopleSoft Wiki version ignores the _nn part. It seems like you could just combine the two regular expressions.

Karmveer Soni said...

Thanks Jim.
I was looking for same in delivered peoplesoft built library but whenever I stuck Java helps to come out of it.