问题描述
虽然这不是本意,但是我们完全将 Groovy 作为脚本语言使用。我们可以像 Java 那样(严谨?)定义变量的类型,又可以像 PHP 那样不用定义变量类型,还能自由使用 Maven 仓库中的包。Groovy 满足我们对脚本语言的全部期望。当然,这些都是个人感受,肯定不符合软件工程的实践要求,但是我们用的很开心。
该笔记将整理:在 Groovy 中,常用的字符串操作,以及常见问题处理。
# 02/19/2021 添加模板引擎的使用方法,无比快乐。
解决方案
极其常用的字符串操作
// 字符串分割(split) // 需要注意,split() 返回 String[] 而不是 List 对象。 "abc,def".split(",") "abc|def".split("\\|") // 使用 Pipe(|) 分割 // 大小写转换 "lowercase".toUpperCase() "UPPERCASE".toLowerCase()
字符串替换:
def mphone = "1+555-555-5555" println mphone.replace(/5/, "3") // 1+333-333-3333 println mphone.replaceFirst(/5/, "3") // 1+355-555-5555 // 替换最后一个字 someStr.replaceAll(" \\S*$", " New Word");
重复字符串若干次(*)
println "#" * 10 println "#".multiply(10)
以行为单位遍历(eachLine)
方法一、使用 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 } // 使用 readLines 分割 def lines = multiline.readLines() // String[] for (line in lines) { // ... }
判断字符串是否匹配正则表达式
使用 ==~ 操作符:
assert "2009" ==~ /\d+/ String regex = /^somedata(:somedata)*$/ assert "somedata" ==~ regex // 注意事项: // 如果是 多行字符串,应该用 =~ 判断,而 ==~ 会返回 false
字符串追加(printf alternative)
据我们所知,函数 printf 只能为字符串追加空格,以使其达到某个长度。
在 Groovy 中,可以使用 padLeft() 或者 padRight() 方法:
println "123123".padLeft(10, "#") // #### 123123
嵌入控制字符
我们需要在字符串中添加控制字符。比如,嵌入 ETX 字符,应该使用 def foo="\u0003" 语句。
使用模板引擎
详细内容,参考 Template engines 文档。
我们这里只进行简单的机械复制,遇到问题在进一步讨论:
def text = 'Dear "$firstname $lastname",\nSo nice to meet you in <% print city %>.\nSee you in ${month},\n${signed}' def binding = ["firstname":"Sam", "lastname":"Pullara", "city":"San Francisco", "month":"December", "signed":"Groovy-Dev"] def engine = new groovy.text.SimpleTemplateEngine() def template = engine.createTemplate(text).make(binding) def result = 'Dear "Sam Pullara",\nSo nice to meet you in San Francisco.\nSee you in December,\nGroovy-Dev' assert result == template.toString()
参考文献
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
Ascii Table – ASCII character codes and html, octal, hex and decimal chart conversion
Control codes – converting to ASCII, hex or decimal
Adding non printable chars to a string in Java? – Stack Overflow
Java String Split Newline – Grails Cookbook
Groovy Goodness: Working with Lines in Strings – Messages from mrhaki
Template engines
Groovy – split() – Tutorialspoint
java – Grails: Splitting a string that contains a pipe – Stack Overflow