50,504
社区成员
发帖
与我相关
我的任务
分享
String s = "<node id=\"04\" text=\"CEC\"><node id=\"0401\" text=\"npar1\">test1</node><node id=\"0402\" text=\"npar1\">test2</node></node>";
String number = "0401";
int index =0;
int start =0;
int end = 0;
Stack<String> stack = new Stack<String>();
String regex1 = "<(\\w+) [^\\>]*\""+number+"\"[^\\>]*>";
String regex2 = "<(/?\\w+)[^\\>]*>";
Pattern p = Pattern.compile(regex1);
Matcher m = p.matcher(s);
if(m.find()){
index = m.end();
start = m.end();
stack.push(m.group(1));
p = Pattern.compile(regex2);
m=p.matcher(s);
String matchStr = null;
while(stack.size()!=0&&m.find(index)){
matchStr = m.group(1);
// System.out.println(matchStr);
if(matchStr.startsWith("/")){
if(matchStr.equals("/"+stack.peek())){
stack.pop();
}
}else{
stack.push(matchStr);
}
index= m.end();
}
if(stack.size()!=0){
throw new Exception("总之是出错了");
}
end = m.start();
System.out.println("结果为:"+s.substring(start,end));
}else{
throw new Exception("没有找到ID为"+number+"的节点");
}
String s = "<node id=\"04\" text=\"CEC\"><node id=\"0401\" text=\"npar1\">test1</node><node id=\"0402\" text=\"npar1\">test2</node></node>";
String number = "04";
String regex = "<(\\w+) [^\\>]*"+number+"[^\\>]*>[^\\<]*</\\1>";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
int index = 0;
while(m.find(index)){
System.out.println(m.group());
index = m.end();
}
String s = "<node id=\"04\" text=\"CEC\"><node id=\"0401\" text=\"npar1\">test1</node><node id=\"0402\" text=\"npar1\">test2</node></node>";
String number = "04";
String regex = "<[^\\>]*"+number+"[^\\>]*>";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
int index = 0;
while(m.find(index)){
System.out.println(m.group());
index = m.end();
}