Regular expression for replacing everything after an underscore in a block of the URL

StackOverflow https://stackoverflow.com/questions/20644311

  •  19-09-2022
  •  | 
  •  

Question

I have the following peoplecode to open a link in new window using new window logic in peoplecode. The following peoplecode and java functions does the job perfectly until a new window is tried to open from an already existing new window which causes the regular expresssion to add one more _newwin which is wrong.

Code

    Function FgNewWinUrl(&strUrl As string) Returns string;
   Local string &sRegex, &sReplace, &Result;
   /* Declare java object */
   Local JavaObject &jUrl;

   /**
    * Peoplesoft Content types:
    * -------------------------
    * Component: c
    * Script: s
    * External: e
    * Homepage: h
    * Template: t
    * Query: q
    * Worklist: w
    * Navigation: n
    * File: f
   **/

   /* Regex strings */
   /*          psc/psp  Site      Portal    Node      Content Type */
   rem &sRegex = "/(ps[cp])/([^\/]*)?/([^\/]*)?/([^\/]*)?/([csehtqwnf]{1})/";

&sRegex = "/(ps[cp])/([^\/]*)?/([^\/]*)?/([^\/]*)?/([csehtqwnf]{1})/";

rem ^[^_]+(?=_);
   &sReplace = "/$1/$2_newwin/$3/$4/$5/";

   /* Instantiate objects and replace */
   &jUrl = CreateJavaObject("java.lang.String", &strUrl);
   &Result = &jUrl.replaceAll(&sRegex, &sReplace);

   /* Return modified URL */
   Return &Result;
End-Function;

Here is my question:

I found a regex to find everything before an underscore. I want to apply that to the second group of the result from regex.

Please let me know how I can do that.

Was it helpful?

Solution

Try this

&sRegex = "/(ps[cp])/([^\/_]*)?(?:_newwin)?/([^\/]*)?/([^\/]*)?/([csehtqwnf]{1})/";

This adds an optional _newwin that is not inclueded in the group count.

If you have to support underscores in the second match we need to rely on greediness…

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top