[英]Groovy vs Jenkins - regex replaceFirst/replaceAll function with closure works differently in Jenkins shared library
[英]How to use Groovy's replaceFirst with closure?
我是Groovy的新手,並且有關於replaceFirst
和閉包的問題。
groovy-jdk API doc給出了一些例子......
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() }
前兩個例子非常簡單,但我無法理解其余的例子。
首先, [one:1, two:2]
是什么意思? 我甚至不知道要搜索它的名字。
第二,為什么有“它”列表? doc說replaceFirst()
通過對該文本的閉包調用的結果替換捕獲的組的第一個匹配項。
“它”不是指“被捕組首次出現”嗎?
我將不勝感激任何提示和評論!
首先, [one:1, two:2]
是一張地圖:
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]
所以我們可以更清楚地重寫代碼,按group
重命名it
( 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()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.