Groovy在同级和父级子女关系中的圆括号之间删除文本 [英] Groovy remove text between parentheses in peer and parent child relationship

查看:120
本文介绍了Groovy在同级和父级子女关系中的圆括号之间删除文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Groovy中,如何在同辈和父母的孩子关系中的圆括号之间删除文本?如 a(b(c)d)返回 a
>

这是我的代码。但它只能处理一个案件。不是都。

  println name.replaceFirst(/\(.*\)/,'')
println name。 replaceAll(/\((.*?)\)/,'')

另一个解决方案是检测括号匹配是对等还是父母对子,并使用正确的RegEx。但我不知道该怎么做。



谢谢,

解决方案

你可以做这种事情,因为正则表达式不会削减它。

  def strip = {status,ch  - > 
switch(ch){
case'(':status.depth ++; break
case')':status.depth--;打破
default:status.str + =(status.depth?'':ch)
}
status
}

assert'a(b (c)d)'。inject([str:'',depth:0],strip).str =='a'
assert'a(b)c(d)'。inject([str: '',depth:0],strip).str =='ac'


In groovy, how to remove text between parentheses in peer and parent child relationship? Such as a(b(c)d) returns a. And a(b)c(d) returns ac?

Here is my code. But it can only handle one case. not both.

println name.replaceFirst( /\(.*\)/, '' ) 
println name.replaceAll( /\((.*?)\)/, '' )

Another solution is to detect if the parentheses match is peer to peer or parent to child and using the right RegEx. But I don't know how.

Thanks,

解决方案

You can do this sort of thing, as regex won't cut it

def strip = { status, ch ->
  switch( ch ) {
    case '(': status.depth++ ; break
    case ')': status.depth-- ; break
    default:  status.str += (status.depth ? '' : ch)
  }
  status
}

assert 'a(b(c)d)'.inject( [ str:'', depth:0 ], strip ).str == 'a'
assert 'a(b)c(d)'.inject( [ str:'', depth:0 ], strip ).str == 'ac'

这篇关于Groovy在同级和父级子女关系中的圆括号之间删除文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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