How to use Groovy replaceFirst with closure?

I am new to Groovy and ask a question about replaceFirstclosing.

groovy -jdk API doc gives me examples ...

assert "hellO world" == "hello world".replaceFirst("(o)") { it[0].toUpperCase() } // first match
assert "hellO wOrld" == "hello world".replaceAll("(o)") { it[0].toUpperCase() }   // all matches

assert '1-FISH, two fish' == "one fish, two fish".replaceFirst(/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() }
assert '1-FISH, 2-FISH' == "one fish, two fish".replaceAll(/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() }

The first two examples are quite simple, but I can not understand the rest.

First, what does it mean [one:1, two:2]? I don’t even know how to look for him.

Secondly, why is there a list of "this"? The document says replaceFirst ()

Replaces the first occurrence of a captured group with the result of calling a closure on this text.

Does this refer to the "first appearance of the captured group"?

I would be grateful for any advice and comments!

+4
source share
1 answer

Firstly, [one:1, two:2]this is a map:

assert [one:1, two:2] instanceof java.util.Map
assert 1 == [one:1, two:2]['one']
assert 2 == [one:1, two:2]['two']
assert 1 == [one:1, two:2].get('one')
assert 2 == [one:1, two:2].get('two')

, , one 1 two 2.

-, , :

, , groupCount -. groupCount int , . groupCount 4, , 4 .

, 0, . , groupCount. , (? , .

:

def m = 'one fish, two fish' =~ /([a-z]{3})\s([a-z]{4})/
assert m instanceof java.util.regex.Matcher
m.each { group ->
    println group
}

:

[one fish, one, fish] // only this first match for "replaceFirst"
[two fish, two, fish]

, it group (it- ):

assert '1-FISH, two fish' == "one fish, two fish".replaceFirst(/([a-z]{3})\s([a-z]{4})/) { group ->
    [one:1, two:2][group[1]] + '-' + group[2].toUpperCase() 
}
assert '1-FISH, 2-FISH' == "one fish, two fish".replaceAll(/([a-z]{3})\s([a-z]{4})/) { group ->
    [one:1, two:2][group[1]] + '-' + group[2].toUpperCase()
}
+2

All Articles