Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy syntax for regular expression matching

Tags:

regex

groovy

What is the Groovy equivalent of the following Perl code?

my $txt = "abc : groovy : def"; if ($txt =~ / : (.+?) : /) {   my $match = $1;   print "MATCH=$match\n";    # should print "MATCH=groovy\n" } 

I know that there's more than one way to do it (including the regular Java way) - but what is the "Groovy way" of doing it?

This is one way of doing it, but it feels a bit clumsy - especially the array notation (m[0][1]) which feels a bit strange. Is there a better way do it? If not - please describe the logic behind m[0][1].

def txt = "java : groovy : grails" if ((m = txt =~ / : (.+?) :/)) {   def match = m[0][1]   println "MATCH=$match" } 
like image 736
knorv Avatar asked Apr 18 '09 22:04

knorv


People also ask

How do you check if a string matches a regex in Groovy?

Groovy regular expressions have a ==~ operator which will determine if your string matches a given regular expression pattern.

How do you write regex in Groovy?

A regular expression is a pattern that is used to find substrings in text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represent the expression for comparison.

How do you match expressions in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

Which of the following is the correct Groovy syntax to match text against a regular expression in Jenkins?

=~ is Groovy syntax to match text against a regular expression.


2 Answers

m[0] is the first match object.
m[0][0] is everything that matched in this match.
m[0][1] is the first capture in this match.
m[0][2] is the second capture in this match.

Based on what I have read (I don't program in Groovy or have a copy handy), given

def m = "barbaz" =~ /(ba)([rz])/; 

m[0][0] will be "bar"
m[0][1] will be "ba"
m[0][2] will be "r"
m[1][0] will be "baz"
m[1][1] will be "ba"
m[1][2] will be "z"

I could not stand not knowing if I was correct or not, so I downloaded groovy and wrote an example:

def m = "barbaz" =~ /(ba)([rz])/;  println "m[0][0] " + m[0][0] println "m[0][1] " + m[0][1] println "m[0][2] " + m[0][2] println "m[1][0] " + m[1][0] println "m[1][1] " + m[1][1] println "m[1][2] " + m[1][2] 
like image 166
Chas. Owens Avatar answered Sep 21 '22 13:09

Chas. Owens


This was the closest match to the Perl code that I could achieve:

def txt = "abc : groovy : def" if ((m = txt =~ / : (.+?) : /)) {   def match = m.group(1)   println "MATCH=$match" }  // Prints: // MATCH=groovy 
like image 37
knorv Avatar answered Sep 21 '22 13:09

knorv