Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract substring in Groovy?

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?

like image 748
IAmYourFaja Avatar asked Jul 31 '14 16:07

IAmYourFaja


People also ask

How do I get part of a string in Groovy?

Groovy - subString() Return Value − The specified substring. String substring(int beginIndex, int endIndex) − Pad the String with the padding characters appended to the right.

How do I fetch a substring?

The substring() method extracts characters, between two indices (positions), from a string, and returns the substring. The substring() method extracts characters from start to end (exclusive). The substring() method does not change the original string.

How do I cut a string in Groovy?

The Groovy community has added a take() method which can be used for easy and safe string truncation. Both take() and drop() are relative to the start of the string, as in "take from the front" and "drop from the front".


2 Answers

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'
like image 128
Will Avatar answered Oct 03 '22 06:10

Will


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

String repoId = str.replaceFirst( /.*&repositoryId=(\w+).*/, '$1' )
like image 32
injecteer Avatar answered Oct 03 '22 07:10

injecteer