永久地址:Groovy之常用字符串操作(保存网址不迷路 🙃)
问题描述
虽然这不是本意,但是我们完全将 Groovy 作为脚本语言使用。我们可以像 Java 那样(严谨?)定义变量的类型,又可以像 PHP 那样不用定义变量类型,还能自由使用 Maven 仓库中的包。Groovy 满足我们对脚本语言的全部期望。当然,这些都是个人感受,肯定不符合软件工程的实践要求,但是我们用的很开心。
该笔记将整理:在 Groovy 中,常用的字符串操作,以及常见问题处理。
# 02/19/2021 添加模板引擎的使用方法,无比快乐。
解决方案
字符串分割(split)
"abc,def".split(",")
// 如果使用 Pipe(|) 进行分割:
"abc|def".split("\\|")
需要注意,split() 返回 String[] 而不是 List 对象。
重复字符串若干次(*)
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
}
判断字符串是否匹配正则表达式
使用 ==~ 操作符:
assert "2009" ==~ /\d+/ String regex = /^somedata(:somedata)*$/ assert "somedata" ==~ regex // 注意事项: // 如果是 多行字符串,应该用 =~ 判断,而 ==~ 会返回 false
使用正则表达式进行字符串替换
def mphone = "1+555-555-5555" println mphone.replace(/5/, "3") // 1+333-333-3333 println mphone.replaceFirst(/5/, "3") // 1+355-555-5555
字符串追加(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()
相关文章
「Groovy」- 常用 MAP 操作
「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
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
本文介绍了Groovy语言中常用的字符串操作方法,包括字符串分割、重复、遍历等实用技巧,并展示了如何使用正则表达式进行匹配和替换。此外,还提供了使用模板引擎简化字符串处理的示例。
769

被折叠的 条评论
为什么被折叠?



