According to Regular expression operators section of https://groovy-lang.org/operators.html, =~
is the find operator, which creates a java.util.regex.Matcher
for pattern to the right matching them on string to the left.
So, dirNumber =~ /0([0-9]+)/
is equivalent to
Pattern.compile("/0([0-9]+)/").matcher(dirNumber)
and evaluates to an instance of java.util.regex.Matcher
.
Groovy gives you the ability to access matches by index ([0]
in your code); your regular expression uses grouping, so in each match you can access groups by (1-based: 0 denotes the entire pattern) index ([1]
in your code), too.
So, your code (if dirNumber
is not null
) extracts the first group of the first match of the regular expression.
// EDITED
You can get an IndexOutOfBoundsException
when the first index ([0]
in your code) is out of the matches' range; when your second index ([1]
in you code) is of the grous' range, you get a null
without exception accessing the group through index...
You can test these scenarios with a simplified version of the code above:
def dirNumber = "Xxx 15 Xxx 16 Xxx 17"
def matcher = dirNumber =~ /Xxx ([0-9]+)/
println(matcher[0][1]) // 15
println(matcher[0][5]) // null
println(matcher[5][1]) // IndexOutOfBoundsException