Groovy:使用“in”运算符获取里面有正则表达式的列表

时间:2012-02-16 10:11:20

标签: regex groovy

有没有办法在“in”运算符中使用regexp里面的列表?

List myList = ["abc", "xyz", ~/a.+z/]

assert ("abc" in myList) == true
assert ("xyz" in myList) == true

assert ("abz" in myList) == true
assert ("aby" in myList) == false

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为没有办法让它与in一起使用。我能想到的最好的方法是编写一个自定义方法,然后像这样运行:

boolean isIn( List domain, String target ) {
  domain.find { target ==~ it }
}

List myList = ["abc", "xyz", ~/a.+z/]

assert ( isIn( myList, "abc" ) ) == true
assert ( isIn( myList, "xyz" ) ) == true
assert ( isIn( myList, "abz" ) ) == true
assert ( isIn( myList, "aby" ) ) == false

实际上,这是可能的,但您需要编写自己的List类:

class MyList extends ArrayList {
  boolean isCase( Object o ) {
    find { o ==~ it }
  }
}

def myList = new MyList()
myList.addAll( ["abc", "xyz", ~/a.+z/] )

assert ("abc" in myList) == true
assert ("xyz" in myList) == true

assert ("abz" in myList) == true
assert ("aby" in myList) == false

或者,覆盖列表的实例元类的isCase方法:

def myList = ["abc", "xyz", ~/a.+z/]
myList.metaClass.isCase = { o ->
  ( delegate.find { o ==~ it } ) as boolean
}
// asserts as before