用于正则表达式匹配的Groovy语法 [英] Groovy syntax for regular expression matching

查看:609
本文介绍了用于正则表达式匹配的Groovy语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下Perl代码的Groovy等价物是什么?

  my $ txt =abc:groovy:def; 
if($ txt =〜/:(。+?):/){
my $ match = $ 1;
打印MATCH = $ match \\\
;
#应打印MATCH = groovy \\\

}

I知道有多种方法可以做到这一点(包括常规的Java方式) - 但是做到这一点的Groovy方法是什么?



这是一种方法这样做,但它感觉有点笨拙 - 特别是数组表示法( m [0] [1] ),这感觉有点奇怪。有没有更好的方法呢?如果不是,请描述 m [0] [1] 背后的逻辑。

 <$ c如果((m = txt =〜/:(。+?):/)){
def match = m [0] [1],$ c> def txt =java:groovy:grails ]
printlnMATCH = $ match
}


解决方案<

  def txt =abc:

这是与我可以实现的Perl代码最接近的匹配: groovy:def
if((m = txt =〜/:(。+?):/)){
def match = m.group(1)
printlnMATCH = $匹配


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"
}

解决方案

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"
}

这篇关于用于正则表达式匹配的Groovy语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆