What does this code do in Groovy?

def host = /\/\/([a-zA-Z0-9-]+(\.[a-zA-Z0-9-])*?)(:|\/)/
assertHost 'http://a.b.c.d:8080/bla', host, 'a.b.c.d'
def assertHost (candidate, regex, expected){
    candidate.eachMatch(regex){assert it[1] == expected}
}

I know that the above code validates my inputs! But on line 4, inside the closure, the magic variable (it) is represented in the array! I'm a little confused. How it works?

How does it work in Groovy (illustrate with simple code)?

+3
source share
1 answer

From http://groovy.codehaus.org/groovy-jdk/java/lang/String.html :

replaceAll

public String replaceAll(String regex, Closure closure)

Replaces all occurrences of a captured group by the result of a closure on that text.
For examples,

assert "hellO wOrld" == "hello world".replaceAll("(o)") { it[0].toUpperCase() }

assert "FOOBAR-FOOBAR-" == "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { Object[] it -> it[0].toUpperCase() })


Here,
     it[0] is the global string of the matched group
     it[1] is the first string in the matched group
     it[2] is the second string in the matched group
+1
source

Source: https://habr.com/ru/post/1796486/


All Articles