2016-10-20 166 views
2

因此,作为学习语言的一部分,我想检查某个模式的三个字符串,并仅返回该模式的第一个匹配项。从字符串列表中获取子字符串

我的尝试是使用find和正则表达式的组合来遍历列表:

def date = [ 
    "some string", 
    "some other string 11.11.2000", 
    "another one 20.10.1990" 
].find { title -> 
    title =~ /\d{2}\.\d{2}\.\d{4}/ 
} 

这类作品,让整个字符串中date

但是,我的目标是在date中以“11.11.2000”结尾;我假设我应该能够访问捕获组,但是如何?

+1

这个问题更适合Stack Overflow。当你移动它时,请为所有那些温暖蓬松的爱情*从这里删除它。* –

+0

@RobertHarvey我似乎缺乏必要的特权。按你的意愿去做,因为我相信你的判断力。 – npst

回答

4

如果您想在集合中找到匹配元素时返回特定值(您的情况可能是该元素的一部分),则需要使用findResult。然后

您的代码可能是这样的

def date = [ 
    "some string", 
    "some other string 11.11.2000", 
    "another one 20.10.1990" 
].findResult { title -> 
    def res = title =~ /\d{2}\.\d{2}\.\d{4}/ 
    if (res) { 
     return res[0] 
    } 
} 
2

扩展UnholySheep的回答,你也可以这样做:

assert [ 
    "some string", 
    "some other string 11.11.2000", 
    "another one 20.10.1990" 
].findResult { title -> 
    def matcher = title =~ /\d{2}\.\d{2}\.\d{4}/ 
    matcher.find() ? matcher.group() : null 
} == '11.11.2000' 

对于所有的比赛,只是用findResults代替findResult,像这样:

assert [ 
    "some string", 
    "some other string 11.11.2000", 
    "another one 20.10.1990" 
].findResults { title -> 
    def matcher = title =~ /\d{2}\.\d{2}\.\d{4}/ 
    matcher.find() ? matcher.group() : null 
} == ['11.11.2000', '20.10.1990'] 
相关问题