Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

regex - Groovy syntax for regular expression matching

What is the Groovy equivalent of the following Perl code?

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

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"
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...