「Groovy」- 常用字符串操作 | String

虽然这不是本意,但是我们完全将 Groovy 作为脚本语言使用。我们可以像 Java 那样(严谨?)定义变量的类型,又可以像 PHP 那样不用定义变量类型,还能自由使用 Maven 仓库中的包。Groovy 满足我们对脚本语言的全部期望。当然,这些都是个人感受,肯定不符合软件工程的实践要求,但是我们用的很开心。

该笔记将整理:在 Groovy 中,常用的字符串操作,以及常见问题处理。

极其常用的字符串操作

// 大小写转换
"lowercase".toUpperCase()
"UPPERCASE".toLowerCase()

startsWith
endsWith

判断为空

How can I determine if a String is non-null and not only whitespace in Groovy? – Stack Overflow

if("") { // false
	
}

if (myString?.trim()) {
  ...
}

包含 | contains(), indexOf(), …

DeepSeek / groovy 判断字符串是否包含特定字符

def str = "Hello, Groovy!"
def containsComma = str.contains(',')  // 判断是否包含逗号
println containsComma  // 输出 true

def str = "Hello, Groovy!"
def hasExclamation = str.indexOf('!') != -1  // 如果找到返回索引,否则返回-1
println hasExclamation  // 输出 true

def str = "Hello, Groovy!"
def hasLetterG = str =~ /G/  // 使用模式匹配操作符 =~
println hasLetterG.find()  // 输出 true

def str = "Hello, Groovy!"
def charToFind = 'o'
def containsChar = charToFind in str
println containsChar  // 输出 true

def str = "Hello, Groovy!"
def charToFind = 'v'
println "字符串${str}${str.contains(charToFind) ? '包含' : '不包含'}字符 ${charToFind}"
// 输出: 字符串Hello, Groovy!包含字符 

// 如果需要检查字符串中是否包含多个特定字符中的任意一个:
def str = "Hello, Groovy!"
def charsToCheck = [',', '!', '?']
def containsAny = charsToCheck.any { str.contains(it) }
println containsAny  // 输出 true

分割 | split()

// 需要注意,split() 返回 String[] 而不是 List 对象。
"abc,def".split(",")
"abc|def".split("\\|") // 使用 Pipe(|)分割

替换 | Replace

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");

重复 | 字符串若干次 | Repeat | *

How can I pad a String in Java? – Stack Overflow

println "#" * 10
println "#".multiply(10)

遍历 | 以行为单位 | eachLine, readLines

Groovy Goodness: Working with Lines in Strings – Messages from mrhaki

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,
    }
}

split

Groovy – split() – Tutorialspoint
java – Grails: Splitting a string that contains a pipe – Stack Overflow
Java String Split Newline – Grails Cookbook

先分割,后遍历:

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
}

注意,split 参数为正则表达式

readLines

通过 readLines 分割:

def lines = multiline.readLines() // String[]

for (line in lines) {
    // ...
}

lines.each {}

追加 | printf alternative

据我们所知,函数 printf 只能为字符串追加空格,以使其达到某个长度。

在 Groovy 中,可以使用 padLeft() 或者 padRight() 方法:

println "123123".padLeft(10, "#") // #### 123123

转义 | 嵌入控制字符

我们需要在字符串中添加控制字符。比如,嵌入 ETX 字符,应该使用 def foo="\u0003" 语句。

模板 | 使用模板引擎

Template engines

# 02/19/2021 添加模板引擎的使用方法,无比快乐。详细内容,参考 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()

String

改 | 修改字符串

Converting a string to int in Groovy – Stack Overflow
Sting to Int: int value = “99”.toInteger()

字符串前缀 | Prefix

originalString.readLines().collect { prefix + it }.join('\n')

格式化 | sprintf

Groovy: Formatted printing with printf and sprintf
Pad a String with Zeros or Spaces in Java | Baeldung

printf('%05d\n', x)