我从客户端获取我的Java应用程序中的以下字符串。
[["UIButton","Submit","15","30","80","80"],["UILabel","User name","15","75","80","80"],["UITextField","Jonathan","15","75","80","80"]]ˇ˛END
我期望解析这个并分别取出3个字符串,如下所示:
"UIButton","Submit","15","30","80","80"
"UIButton","Submit","15","30","80","80"
"UIButton","Submit","15","30","80","80"
我试过如下,
// resultStr = [["UIButton","Submit","15","30","80","80"],["UILabel","User name","15","75","80","80"],["UITextField","Jonathan","15","75","80","80"]]ˇ˛END
if ( resultStr.length()>0 && resultStr!=null ) {
for (int i=0; i<resultStr.length(); i++) {
int startInd = resultStr.indexOf('[');
int endInd = resultStr.indexOf(']');
if ( startInd>=0 && endInd>0 ) {
String resStr = resultStr.substring(startInd , endInd);
if ( resStr!=null )
System.out.println("Applet resStr: " + resStr);
}
else
System.out.println("Applet startindex, endindex failed");
}
}
但是,这不起作用,这不正确地解析我所期望的。有人可以建议如何按预期分别解析字符串吗?
答案 0 :(得分:1)
您可以使用String.split()
方法分割此字符串:
String[] t = myString.substring(2, s.length()-7).split("\\],\\[");
所以你的代码看起来像这样:
//resultStr = [["UIButton","Submit","15","30","80","80"],["UILabel","User name","15","75","80","80"],["UITextField","Jonathan","15","75","80","80"]]ˇ˛END
if ( resultStr.length()>7 && resultStr!=null ) {
String[] resStrings = resultStr.substring(2, resultStr.length()-7).split("\\],\\[");
for (String resString: resStrings) {
System.out.println("Applet resStr: " + resStr);
}
}
因此,您应该有以下输出:
Applet resStr: "UIButton","Submit","15","30","80","80"
Applet resStr: "UILabel","User name","15","75","80","80"
Applet resStr: "UITextField","Jonathan","15","75","80","80"
答案 1 :(得分:0)
使用 Lazy 方式和Lookaround
尝试使用模式和匹配器(?<=\[).*?(?=\])
OR possessive量词
(?<=\[)[^]]*+(?=\])
示例代码:
Matcher matcher = Pattern.compile("(?<=\\[).*?(?=\\])").matcher(strring);
while (matcher.find()) {
System.out.println(matcher.group());
}