Reputation: 127
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
Upvotes: 1
Views: 1349
Reputation: 27756
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
.\{\[.+?\]\}
\{\[
- 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 RegExecho
by println
).Upvotes: 2
Reputation: 27220
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]}'
Upvotes: 3