Reputation: 165
Is there any way to use the "in" operator for a list with a regexp inside?
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
Thanks for any help.
Upvotes: 2
Views: 1998
Reputation: 171084
I don't think there's a way to get this to work with in
. The best I can think of is to write a custom method, and running that instead like so:
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
Actually, this is possible, but you'll need to either write your own List
class:
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
Or, overwrite the isCase
method on the instance meta class for your list:
def myList = ["abc", "xyz", ~/a.+z/]
myList.metaClass.isCase = { o ->
( delegate.find { o ==~ it } ) as boolean
}
// asserts as before
Upvotes: 2