正则表达式以获取重复组

时间:2014-11-25 10:40:07

标签: java regex

我有以下文本需要检索特定信息(可能是多行):

Type [Hello] Server [serverName]. [BC]. [CD] [D" +
                "E]. [FH]. [MN]. [CS]., ID = 53ec9d"

从我需要检索的文字:

serverName以及由[]分隔的" ."内的以下条目。他们可以重复任何次数。他们的结尾用".,".

表示

所以在上面的例子中我的输出应该是:

serverName : serverName

和值应该是:

BC , CD, DE,FH, MN,CS

需要帮助。

2 个答案:

答案 0 :(得分:0)

对于想法运行:

public static void main(String[] args) {
    String s = "Type [Hello] Server [serverName]. [BC]. [CD] [DE]. [FH]. [MN]. [CS]., ID = 53ec9d";

    /*
     * anything that is surrounded by [ ] characters and doesn't contain [ ]
     */
    Pattern compile = Pattern.compile("\\[([^\\[\\]]+)\\]");
    Matcher matcher = compile.matcher(s);

    boolean first = true, second = true;
    while (matcher.find()) {

        if (first) { // avoiding [Hello]
            first = false;
            continue;
        }

        // remove surrounding [ ]
        String currentValue = matcher.group(1).replaceAll("\\[|\\]", "");

        // first find is treated differently
        if (second) {
            second = false;
            System.out.println("serverName = " + currentValue);
            continue;
        }

        System.out.println(currentValue);
    }
}

输出是:

serverName = serverName
BC
CD
DE
FH
MN
CS

答案 1 :(得分:0)

.,.*$|Server\s*\[([^\]]*)|\.\s+\[([^\]]*)

你可以试试这个。看看demo.Grab捕获。

http://regex101.com/r/rA7aS3/5

相关问题