Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there named groups in Groovy regex pattern matches?

Tags:

regex

groovy

Something like:

def match = "John 19" =~ /(&name&)\w+ (&age&\d+)/
def name = match.name
def age = match.age

Is there a groovy syntax that allows for something like this (instead of of the fictional & operator I made up?

like image 628
ripper234 Avatar asked Mar 27 '13 16:03

ripper234


People also ask

How do I match a group in regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".

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.

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

Assuming you are using on Java 7+, you can do:

def matcher = 'John 19' =~ /(?<name>\w+) (?<age>\d+)/
if( matcher.matches() ) {
  println "Matches"
  assert matcher.group( 'name' ) == 'John'
  assert matcher.group( 'age' ) == '19'
}
else {
  println "No Match"
}

If you are not on java 7 yet, you'd need a third party regex library

like image 188
tim_yates Avatar answered Oct 19 '22 22:10

tim_yates


This doesn't name the groups, but a closure does parameterise the match:

("John 19" =~ /(\w+) (\d+)/).each {match, name, age ->
  println match
  println name
  println age
}

which outputs:

John 19
John
19

This is a useful reference: http://naleid.com/blog/2008/05/19/dont-fear-the-regexp/

like image 20
natke Avatar answered Oct 19 '22 20:10

natke