Groovy - 从String中提取并显示子字符串

时间:2014-10-07 01:05:53

标签: groovy

我想从下面的字符串中找到一个模式。所有单词都包含“MATCH.TEXT3”,可能是最新的与结尾数字匹配的。

{MATCH.TEXT1.1=[1, admin, 07/10/14 09:29:34], MATCH.TEXT2.2=[2, admin, 07/10/14 10:01:08], MATCH.TEXT3.3=[3, admin, 07/10/14 10:08:01], MATCH.TEXT3.4=[4, admin, 07/10/14 11:08:01], MATCH=[TEXT3]}

预期产出:

MATCH.TEXT3.4

or

MATCH.TEXT3.3
MATCH.TEXT3.4

2 个答案:

答案 0 :(得分:5)

您可以对字符串使用findAll()方法来提取与给定模式匹配的标记:

String s = '{MATCH.TEXT1.1=[1, admin, 07/10/14 09:29:34], MATCH.TEXT2.2=[2, admin, 07/10/14 10:01:08], MATCH.TEXT3.3=[3, admin, 07/10/14 10:08:01], MATCH.TEXT3.4=[4, admin, 07/10/14 11:08:01], MATCH=[TEXT3]}'

List<String> tokens =  s.findAll(/MATCH\.TEXT3(\.[0-9]+)?/)

assert tokens == ['MATCH.TEXT3.3', 'MATCH.TEXT3.4']

String last = tokens.last()

assert last == 'MATCH.TEXT3.4'

答案 1 :(得分:1)

最后一场比赛:

class Finder {
    static main(args) {
        def str = '''<your string>'''
        def textFinder= /(MATCH.TEXT3.\d+)/
        def textMatcher = str=~textFinder
        if(textMatcher.size()>0){
            def lastMatch = (Integer) textMatcher.size() - 1
            println (textMatcher=textMatcher[lastMatch][1])         
        }
    }
}

输出:
MATCH.TEXT3.4

所有比赛都很容易改变。