这段代码在Groovy中做了什么?

时间:2011-03-05 12:24:05

标签: 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}
}

我知道上面的代码断言我的输入!但是在第4行,在闭包内部,魔术变量(it)以数组形式表示!我有点困惑。它是如何工作的?

这在Groovy中如何工作(用简单的代码说明)?

1 个答案:

答案 0 :(得分:1)

来自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