我的输入字符串是这样的:
String msgs="<InfoStart>\r\n"
+ "id:1234\r\n"
+ "phone:912119882\r\n"
+ "info_type:1\r\n"
+<InfoEnd>\r\n"
+"<InfoStart>\r\n"
+ "id:5678\r\n"
+ "phone:912119881\r\n"
+ "info_type:1\r\n"
+<InfoEnd>\r\n";
现在我可以使用正则表达式来获取信息数组:
private static Pattern patter= Pattern.compile("InfoStart>([\\s\\S]*?)<InfoEnd>");
,但是如何使用正则表达式获取ID,电话?我尝试编写代码,但失败了,如何解决?
private static Pattern infP = Pattern.compile("<InfoStart>([\\s\\S]*?)<InfoEnd>");
private static Pattern lineP = Pattern.compile(".*?\r\n");
final java.util.regex.Matcher matcher = patter.matcher(msgs);
while (matcher.find()){
String item = matcher.group(1);
Matcher matcherLine = lineP.matcher(item);
while(matcherLine.find()){
if(matcherLine.groupCount()>0){
String value= matcherLine.group(1);
int firstIndex=value.indexOf(":");
System.out.println("key:"+value.substring(0, firstIndex)+"value:"+value.substring(firstIndex+1));
}
}
}
答案 0 :(得分:1)
也许您可以尝试以下方法:
{{dataHash}}
输出:
Pattern xmlPattern = Pattern.compile("<InfoStart>\\s+id:(\\d+)\\s+phone:(\\d+)\\s+info_type:(\\d+)\\s+<InfoEnd>");
Matcher matcher = xmlPattern.matcher(msgs);
while (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(3));
}
但是我还是不得不提Tim Biegeleisen所说的,您最好使用其他方法来解析 XML 字符串。
此外,您输入的字符串不正确,应该是:
1234
912119882
1
5678
912119881
1