How to extract substring in Groovy?

30,000

Solution 1

There are a lot of ways to achieve what you want. I'll suggest a simple one using split:

sub = { it.split("repositoryId=")[1] }

str='wsodk3oke30d30kdl4kof94j93jr94f3kd03k043k?planKey=si23j383&repositoryId=31850514'

assert sub(str) == '31850514'

Solution 2

Using a regular expression you could do

def repositoryId = (str =~ "repositoryId=(.*)")[0][1]

The =~ is a regex matcher

Solution 3

or a shortcut regexp - if you are looking only for single match:

String repoId = str.replaceFirst( /.*&repositoryId=(\w+).*/, '$1' )
Share:
30,000
IAmYourFaja
Author by

IAmYourFaja

my father is a principal at burgoyne intnl and got me this job programming lisp and development. I aspire to unittesting with a concentration in mobile platforms.

Updated on July 05, 2022

Comments

  • IAmYourFaja
    IAmYourFaja almost 2 years

    I have a Groovy method that currently works but is real ugly/hacky looking:

    def parseId(String str) {
        System.out.println("str: " + str)
        int index = href.indexOf("repositoryId")
        System.out.println("index: " + index)
        int repoIndex = index + 13
        System.out.println("repoIndex" + repoIndex)
        String repoId = href.substring(repoIndex)
        System.out.println("repoId is: " + repoId)
    }
    

    When this runs, you might get output like:

    str: wsodk3oke30d30kdl4kof94j93jr94f3kd03k043k?planKey=si23j383&repositoryId=31850514
    index: 59
    repoIndex: 72
    repoId is: 31850514
    

    As you can see, I'm simply interested in obtaining the repositoryId value (everything after the = operator) out of the String. Is there a more efficient/Groovier way of doing this or this the only way?

  • injecteer
    injecteer almost 10 years
    the = is missing :)
  • IgorGanapolsky
    IgorGanapolsky over 7 years
    I get an error: no such property sub for class: org.gradle.api.internal.project.DefaultProject_Decorated
  • Will
    Will over 7 years
    @IgorGanapolsky are you running it from a script? try adding a def in front of sub.
  • OK999
    OK999 almost 7 years
    @Will, how do i get only the say next number and not the trailing ones after that? your solution is returning everything after the keyword. e.g. i have the String, "Request ID for the current retrieve task: 09Sg00000052eIJEAY [sf:retrieve] Waiting for server to finish processing the request...". I am trying to get only "09Sg00000052eIJEAY". I know i have to modify the index. But i can't figure so far
  • OK999
    OK999 almost 7 years
    Got it!!! def sub = { it.split("current retrieve task: ")[1][0..18] } .... Upvoted the answer :)