Reputation: 17906
whats the common way of solving a situation where you have a text
this is an awesome text and nothing else matters
and i have a List like
[ "nothing","bread","butter","fool" ]
and i want to check if any of the words in the String is inside the list
my soulution so far is :
Boolean check = false
String myString = "this is an awesome text and nothing else matters"
List myList = [ "nothing","bread","butter","fool" ]
def stringlist = myString.tokenize(" ")
stringlist.each{
if( it in myList ){
check = true
}
}
Is there a more performant or better elegant way to handle this ?
How do i handle punctuation marks ?
For any suggestions thanks in advance
Upvotes: 2
Views: 1205
Reputation: 7619
One of the way to handle punctuation marks is
String myString = "for example: this string, is comma separated and a colon is inside - @Self"
List myList = ["nothing", "bread", "butter", "fool", "example", "string", "Self"]
Boolean check = false
myList.each {
if (myString.contains(it)) {
check = true
}
}
Upvotes: 1
Reputation: 50245
Extending what Joshua has pointed out (using intersect) and adding a regex (considering the simplest case of string [alphanumeric]), something like below can be done:
String myString = "for example: this string, is comma seperated
and a colon is inside - @Self"
List myList = [ "nothing","bread","butter","fool", "example", "string", "Self" ]
assert myString.split(/[^a-zA-Z0-9]/).toList().intersect(myList)
== ["example", "string", "Self"]
Also note, intersect returns the conjunction of those two collections which you can apply as Groovy truth as well ([]
is false of both lists are disjoint)
Upvotes: 3
Reputation: 24776
I would look at using some of the collection methods. Intersect comes to mind.
def myString = "this is my string example"
def words = ['my', 'list', 'of', 'stuff']
def matches = myString.tokenize(" ").intersect(words)
println matches
def check = (matches.size() > 0)
Upvotes: 3