字串分割
Groovy - split() - Tutorialspoint java - Grails: Splitting a string that contains a pipe - Stack Overflow
"abc,def".split(",")// 如果使用 Pipe(|) 進行分割:"abc|def".split("\\|")
將字串作為文字行進行遍歷
Java String Split Newline - Grails Cookbook Groovy Goodness: Working with Lines in Strings - Messages from mrhaki
方法一、使用 eachLine 進行遍歷:
def multiline = '''\Groovy is closely related to Java,so it is quite easy to make a transition.'''multiline.eachLine { if (it =~ /Groovy/) { println it // Output: Groovy is closely related to Java, }}
方法二、先分割,後遍歷:
def multiline = '''\Groovy is closely related to Java,so it is quite easy to make a transition.'''def lines = multiline.split("\\r?\\n");for (String line : lines) { println line}
判斷字串是否匹配正則表示式
使用 ==~ 運算子:
assert "2009" ==~ /\d+/String regex = /^somedata(:somedata)*$/assert "somedata" ==~ regex
使用正則表示式進行字串替換def mphone = "1+555-555-5555"println mphone.replace(/5/, "3")// 1+333-333-3333println mphone.replaceFirst(/5/, "3")// 1+355-555-5555
字串追加(printf alternative)
據我們所知,函式 printf 只能為字串追加空格,以使其達到某個長度。
在 Groovy 中,可以使用 padLeft() 或者 padRight() 方法:
println "123123".padLeft(10, "#") // ####123123
相關文章
「Apache Groovy」- 常用列表(List)操作
參考文獻Simple Groovy replace using regex - Stack Overflow java - How to check if a String matches a pattern in Groovy - Stack Overflow Pad a String with Zeros or Spaces in Java | Baeldung How can I pad a String in Java? - Stack Overflow
最新評論