groovy if 判断字符串_「Groovy」- String(学习笔记) @20210213

本文介绍了Groovy中如何使用`split`进行字符串分割,通过`eachLine`或先分割后遍历的方式处理多行文本,以及利用`==~`操作符判断字符串是否匹配正则表达式。此外,还展示了正则表达式在字符串替换中的应用,并提到了`padLeft`和`padRight`方法用于字符串追加。
摘要由CSDN通过智能技术生成

字符串分割

"abc,def".split(",")

// 如果使用 Pipe(|) 进行分割:

"abc|def".split("\\|")

将字符串作为文本行进行遍历

方法一、使用 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-3333

println mphone.replaceFirst(/5/, "3")

// 1+355-555-5555

字符串追加(printf alternative)

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

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

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

相关文章

参考文献

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值