有没有办法在“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
感谢您的帮助。
答案 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