我有以下文本需要检索特定信息(可能是多行):
Type [Hello] Server [serverName]. [BC]. [CD] [D" +
"E]. [FH]. [MN]. [CS]., ID = 53ec9d"
从我需要检索的文字:
serverName
以及由[]
分隔的" ."
内的以下条目。他们可以重复任何次数。他们的结尾用".,".
所以在上面的例子中我的输出应该是:
serverName : serverName
和值应该是:
BC , CD, DE,FH, MN,CS
需要帮助。
答案 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)