I have a string
in a jenkinsfile
and I am trying to create a new variable based on a regex match of that string. For example:
def stringA = "Hello World Today"
def stringB = stringA =~ /Hello/
echo stringB
I expect to see Hello
echo in the console but I only get what seems to be a reference to a regex object.
I cannot seem to achieve what I am trying.
In this situation, stringB
would indeed be assigned a value of a regular expression object. You need to use the syntax to capture a substring within the regular expression. This is ()
in Groovy and most other interpreted languages as well:
def stringB = stringA =~ /(Hello)/
The value of stringB
at this point would be a nested array where each element is an array containing values for the matching substring of each ()
within the regular expression. In this situation, there is only one ()
, so we access the zeroth element and then the nested element containing the substring for the match, which is the element at one:
print stringB[0][1]
This will return Hello
.