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