Home > Software engineering >  Jenkins/Groovy: How to pull specific part of a string
Jenkins/Groovy: How to pull specific part of a string

Time:05-03

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

CodePudding user response:

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]}'

CodePudding user response:

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).
  • Related