[英]Remove prefix from string in Groovy
如果字符串開始,我需要從 Groovy 中的字符串中刪除前綴(否則不執行任何操作)。
如果前綴是groovy
:
groovyVersion
我期望Version
groovy
我期望空字符串spock
我期待spock
現在我使用.minus()
,但是當我這樣做時
'library-groovy' - 'groovy'
然后結果我得到library-
而不是library-groovy
。
實現我想要的東西的常規方法是什么?
我不太了解 Groovy,但這是我對這個的看法:
def reg = ~/^groovy/ //Match 'groovy' if it is at the beginning of the String
String str = 'library-groovy' - reg
println(str)
這是區分大小寫的,不使用正則表達式:
def prefix = 'Groovy';
def string = 'Groovy1234';
def result = '';
if (string.startsWith(prefix)) {
result = string.substring(prefix.size())
print result
}
這個版本簡單明了,但它滿足要求並且是對原始版本的增量更改:
def trimGroovy = {
it.startsWith('groovy') ? it - 'groovy' : it
}
assert "Version" == trimGroovy("groovyVersion")
assert "" == trimGroovy("groovy")
assert "spock" == trimGroovy("spock")
assert "library-groovy" == trimGroovy("library-groovy")
如果Groovy中以字符串開頭,則需要從String中刪除前綴(否則不執行任何操作)。
如果前綴是groovy
:
groovyVersion
我期望Version
groovy
我期望空字符串spock
我希望spock
現在我使用.minus()
,但是當我這樣做時
'library-groovy' - 'groovy'
結果我得到了library-
而不是library-groovy
。
實現我想要的目標的常規方法是什么?
你應該使用正則表達式:
assert 'Version spock' == 'groovyVersion groovy spock'.replaceAll( /\bgroovy/, '' )
解決方案:使用-
運算符並剪切正確的字符串。
def sentence = "remove_me_i_am_ok"
def string_to_be_remove = "remove_me_"
String result = sentence - string_to_be_remove
print("output: ${result}")
/* output: i_am_ok */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.