Elegant way for pattern matches with List-entrys Groovy

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

Answers


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)

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)


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 
    }
}

Need Your Help

iOS 7 does not call layoutSubviews

ios objective-c ios6 ios7

I am transitioning my iOS 6 app to iOS 7 and have a few problems.

Assigning a value to a variable in a loop and printing it using korn shell

unix

I am having problem when trying to assign a value to a variable in a loop and trying to print it using korn shell. I want to use that variable in later part of my script. So I am trying to test wit...