日期:2014-05-18 浏览次数:20767 次
var s="<record>" +"<name>张三</name>" +"<age>23</age>" +"<sex>男</sex>" +"</record>" +"<record>" +"<name>李四</name>" +"<age>23</age>" +"<sex>男</sex>" +"</record>" +"<record>" +"<name>王五</name>" +"<age>23</age>" +"<sex>男</sex>" +"</record>" /*获取子匹配*/ var oReg1=/<name>(.*?)<\/name>/; alert(s.match(oReg1)[1]); /*获取所有匹配*/ var oReg2=/<name>(.*?)<\/name>/g; var result=s.match(oReg2) .join("") .replace(/<name>/g,"") .replace(/<\/name>/g,""); alert(result);
public static void main(String[] args) { String str = "<record>" + "<name>张三</name>" + "<age>23</age>" + "<sex>男</sex>" + "</record>" + "<record>" + "<name>李四</name>" + "<age>23</age>" + "<sex>男</sex>" + "</record>" + "<record>" + "<name>王五</name>" + "<age>23</age>" + "<sex>男</sex>" + "</record>"; String[] strArray = getElementsByTag("name", str); for (String ss : strArray) { System.out.println(ss.replaceAll("<name>", "").replace("</name>", "")); } } public static String[] getElementsByTag(String tagName, String str) { Pattern p = Pattern.compile("<" + tagName + "[^>]*?((>.*?</" + tagName + ">)|(/>))"); Matcher m = p.matcher(str); ArrayList<String> al = new ArrayList<String>(); while (m.find()) { al.add(m.group()); } String[] arr = al.toArray(new String[al.size()]); al.clear(); return arr; }