IAmYourFaja
IAmYourFaja

Reputation: 56914

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?

Upvotes: 13

Views: 52275

Answers (4)

Foxy Fox
Foxy Fox

Reputation: 491

All the answers here contains regular expressions, however there are a bunch of string methods in Groovy.

String Function Sample Description
contains myStringVar.contains(substring) Returns true if and only if this string contains the specified sequence of char values
equals myStringVar.equals(substring) This is similar to the above but has to be an exact match for the check to return a true value
endsWith myStringVar.endsWith(suffix) This method checks the new value contains an ending string
startsWith myStringVar.startsWith(prefix) This method checks the new value contains an starting string
equalsIgnoreCase myStringVar.equalsIgnoreCase(substring) The same as equals but without case sensitivity
isEmpty myStringVar.isEmpty() Checks if myStringVar is populated or not.
matches myStringVar.matches(substring) This is the same as equals with the slight difference being that matches takes a regular string as a parameter unlike equals which takes another String object
replace myStringVar.replace(old,new) Returns a string resulting from replacing all occurrences of oldChar in this string with newChar
replaceAll myStringVar.replaceAll(old_regex,new) Replaces each substring of this string that matches the given regular expression with the given replacement
split myStringVar.split(regex) Splits this string around matches of the given regular expression

Upvotes: 3

Jeff Storey
Jeff Storey

Reputation: 57192

Using a regular expression you could do

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

The =~ is a regex matcher

Upvotes: 16

injecteer
injecteer

Reputation: 20699

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

String repoId = str.replaceFirst( /.*&repositoryId=(\w+).*/, '$1' )

Upvotes: 2

Will
Will

Reputation: 14529

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'

Upvotes: 21

Related Questions