如何在Groovy数组中为%grep?

时间:2018-12-05 23:02:58

标签: groovy

给出下面的Groovy数组(注意%):

def list = ["H 11 * * * % env=TEST;state=UP"]

有没有一种方法可以检查数组元素是否包含%?

我尝试了Groovy的“ find”,“ findAll”和“ any”方法的各种组合,但是它们仅匹配整个字符串,而不匹配单个字符。

grep似乎是解决方案,但是当我尝试这样的操作时:

def name = list.grep(~/%/)
println(name)

它只打印[]。

我想测试%是否出现在数组元素中的任何地方。

3 个答案:

答案 0 :(得分:1)

grep可以像您一样用来过滤数组。它将返回所有符合条件的元素。

唯一的问题是您使用的正则表达式应该是~/.*%.*/而不是~/%/


顺便说一句,findAll也可以像grep一样工作:

list.findAll { s -> s ==~ /.*%.*/ }​

运算符==~是正则表达式的匹配器。


如果您只是想获取真实性(真/假),请检查至少一个元素是否符合条件,any也会起作用:

list.any { s -> s ==~ /.*%.*/ }​

答案 1 :(得分:0)

您必须告诉正则表达式可选地将%之前和之后的字符与.*或类似字符进行匹配,也就是说,这应该可行:

list.grep(~/.*%.*/)

答案 2 :(得分:0)

一个稍微不同的选项。

WITH NumberedDates AS (
SELECT
City
,Booking
,Purchase_Date
, Purchaser_Email
,Guest_Info
,Addr_1
,City_7
,State_Province
,Country
, Gross_Sales
, Event_Date
, Event_Name
, MIN(Event_Date) OVER (PARTITION BY Purchaser_Email) as minPurchDate
, ROW_NUMBER() OVER (PARTITION BY Purchaser_Email ORDER BY Event_Date) AS RowNo
FROM SalesEatingEurope.DymTable )



SELECT
n1.City
, n1.Booking
, n1.Purchase_Date
, n1.Purchaser_Email
, n1.Guest_Info
, n1.Addr_1
, n1.City_7
, n1.State_Province
, n1.Country
, n1.Gross_Sales
, n1.Event_Name
, n1.Event_Date
, n1.RowNo as TransactionNumber
, n2.Event_Date as PrevEventDate
, IFNULL(date_diff(EXTRACT(DATE FROM n2.Event_Date), EXTRACT(DATE FROM n1.Event_Date) ,day), 0)*-1 AS DaysSincePrevEvent
, n1.minPurchDate as FirstEvent
, IFNULL(date_diff( EXTRACT(DATE FROM n1.minPurchDate), EXTRACT(DATE FROM n1.Event_Date) ,day), 0)*-1 AS DaysSinceFirstEvent
FROM NumberedDates  AS n1
LEFT JOIN NumberedDates  AS n2
ON n1.Purchaser_Email = n2.Purchaser_Email
AND n1.RowNo = n2.RowNo + 1
ORDER BY n1.Purchaser_Email, n1.Event_Date