groovyjenkins-pipeline

Groovy way to get part of this URL?


I have the following URL string.

https://my.reportUrl.com/scans#~%2528cicd_scan~%2527800172eb-d004-4237-b8e6-797bde26a1ab%252A2c2025-02-04T20%2525%25252A3a16%2525%25252A3a38.511117722Z%2527%2529

What is a Groovy way to get the

https://my.reportUrl.com/scans#~%2528cicd_scan~%2527800172eb-d004-4237-b8e6-797bde26a1ab%252A2c2025-02-04T20%2525%25252A3a16%2525%25252A3a38

part? That is, the part before the last "." in the URL. I know I can string.tokenize(".") and then just concatenate the parts I want, but there's got to be a better, groovier, way?


Solution

  • There are indeed a number of ways to obtain the result from the input string, and it seems like the question is for a path forward that is clean and efficient. I would then recommend a regular expression with a matcher:

    def shortUrlRegexp = 'https://my.reportUrl.com/scans#~%2528cicd_scan~%2527800172eb-d004-4237-b8e6-797bde26a1ab%252A2c2025-02-04T20%2525%25252A3a16%2525%25252A3a38.511117722Z%2527%2529' =~ /(.*)\./ // greedy regular expression that you can modify as necessary
    String shortUrl = shortUrlRegexp[0][1] // assign value from matched string
    shortUrlRegexp = null // avoids an error due to inability to serialize
    

    Depending upon the type you could use the ==~ operator instead of =~ for the regular expression, but that depends on your potential use cases.