求一个用java的正则获取子匹配的hello world 程序
客户端的正则比较容易,服务器端的没有写过,希望能用java的正则对象来实现如下功能
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;}