模式匹配的优雅方式与List-entrys Groovy

时间:2014-03-10 16:08:11

标签: list groovy

解决你有文本的情况的常用方法

  

这是一篇很棒的文字,没有其他重要的事情

我有一个像

这样的列表
[ "nothing","bread","butter","fool" ]

我想检查字符串中的任何单词是否在列表中

到目前为止,我的洗礼是:

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

是否有更高性能或更优雅的方式来处理这个问题?

我如何处理标点符号?

提前感谢任何建议

3 个答案:

答案 0 :(得分:3)

我会考虑使用一些收集方法。想到Intersect

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)

答案 1 :(得分:3)

扩展约书亚指出的内容(使用交叉)并添加正则表达式(考虑最简单的字符串[字母数字]),可以这样做:

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"]

另请注意,intersect返回这两个集合的连接,您可以将它们应用为Groovy真值([]为false,两个列表都是不相交的)

答案 2 :(得分:1)

处理标点符号的方法之一是

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