'Jenkins/Groovy: How to pull specific part of a string

I have a string that look like:

data = ABSIFHIEHFINE -2938 NODFNJN {[somedate]} oiejfoen

I need to pull {[somedate]} only with {[]} included. I tried to do data.substring(0, data.indexOf(']}')) to remove the end of the string but it is also removing the symbols that I need to keep



Solution 1:[1]

I need to pull {[somedate]} only with {[]} included.

def data = 'ABSIFHIEHFINE -2938 NODFNJN {[somedate]} oiejfoen'

// you could do error checking on these to ensure
// >= 0 and end > start and handle that however 
// is appropriate for your requirements...
def start = data.indexOf '{['
def end = data.indexOf ']}'

def result = data[start..(end+1)]

assert result ==  '{[somedate]}'

Solution 2:[2]

You can do it using regular expression search:

data = "ABSIFHIEHFINE -2938 NODFNJN {[somedate]} oiejfoen"
def matcher = data =~ /\{\[.+?\]\}/
if( matcher ) {
    echo matcher[0]
}
else {
    echo "no match"
}

Output:

{[somedate]}

Explanations:

  • =~ is the find operator. It creates a java.util.regex.Matcher.
  • The string between the forward slashes (which is just another way to define a string literal), is the regular expression: \{\[.+?\]\}
  • RegEx breakdown:
    • \{\[ - literal { and [ which must be escaped because they have special meaning in RegEx
    • .+? - any character, at least one, as little as possible (to support finding multiple sub strings enclosed in {[]})
    • \]\} - literal ] and } which must be escaped because they have special meaning in RegEx
  • You can test the RegEx only or use Groovy IDE to test the full sample code (replace echo by println).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2