Regular expression in Groovy

How to use Regular expression in Groovy

Basic syntax:

//: Define regular expressions in which special characters are automatically escaped

example: Pattern regex= "\\d+\\.\\d+",

In groovy we can define like this: def regex = /\d+\.\d+/

~//: defines a regular expression that compiles the string into Pattern

=~: matches the left string locally with the right regular expression and returns a Matcher

==~: globally matches the left string to the right regular expression and returns Boolean

Example:

def ProductVersion = "13.1.0"
def regex = /\d+\.\d+/;
//def match = ProductVersion=~regex;
//def version = match[0]
def version = (ProductVersion=~regex)[0]
 
echo "version : ${version }" //printf: 13.1

Trouble Shoot:

If using the code like below which Be commented in the above example

def match = ProductVersion=~regex;
def version = match[0]

It will cause an exception like this:

java.io.NotSerializableException: java.util.regex.Matcher
Not sure this is a bug in groovy, the solution is:
def version = (ProductVersion=~regex)[0]

Related links:

https://blog.csdn.net/somilong/article/details/78865031

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值