问题描述
<div class="hdwiki_tmml"><a class=" FCK__AnchorC" name="1">是大家是否</a></div><div class="hdwiki_tmml"><a name="2">士大夫士大夫</a></div>我想要的结果是:1.是文字内容是大家是否士大夫士大夫2。是name的值12麻烦帮忙解决下 java的后台 问题补充:飞雪无情 写道
解决方案
引用http://www.oschina.net/p/jsouposchina推荐,不知道好不好用
解决方案二:
看了我上面写的那个分开的正则表达式,就是一个匹配内容,一个匹配属性值的。那么下面这个用一个正则表达式匹配他们两个你就好理解了!public static void main(String[] args) {String source="<div class="hdwiki_tmml"><a class=" FCK__AnchorC" name="1">是大家是否</a></div><div class="hdwiki_tmml"><a name="2">士大夫士大夫</a></div> ";StringBuilder resultComment=new StringBuilder();StringBuilder resultName=new StringBuilder();System.out.println("=======开始匹配========");String patternStrs="(<div class="hdwiki_tmml"><a.+?)name="(.+?)">(.+?)(</a></div>)";Pattern pattern=Pattern.compile(patternStrs);Matcher matcher=pattern.matcher(source);while(matcher.find()){resultName.append(matcher.group(2)+"n");resultComment.append(matcher.group(3)+"n");}System.out.println("=======标签内内容=======");System.out.println(resultComment.toString());System.out.println("=======name属性值=======");System.out.println(resultName.toString());}一个正则表达式搞定,节省了代码!
解决方案三:
没劲var result1=[],result2=[]var s='<div class="hdwiki_tmml"><a class=" FCK__AnchorC" name="1">是大家是否</a></div> <div class="hdwiki_tmml"><a name="2">士大夫士大夫</a></div> ' var reg=/(<(w+)s?.*?>)([^<].*?[^>])(</2>)/ig var match=s.match(reg)var reg1=/name="(.*?)"/var reg2=/>(.*?)</for(i=0;i<match.length;i++){reg1.test(match[i])result1.push(RegExp.$1)reg2.test(match[i])result2.push(RegExp.$1)}alert(result1)alert(result2)
解决方案四:
正则好久不用手都生了,不过终于把代码写出来了。测试通过。public static void main(String[] args) {String source="<div class="hdwiki_tmml"><a class=" FCK__AnchorC" name="1">是大家是否</a></div><div class="hdwiki_tmml"><a name="2">士大夫士大夫</a></div> ";StringBuilder result=new StringBuilder();System.out.println("=======开始匹配文字内容========");String patternStrs="(<div class="hdwiki_tmml"><a.+?>)(.+?)(</a></div>)";Pattern pattern=Pattern.compile(patternStrs);Matcher matcher=pattern.matcher(source);while(matcher.find()){result.append(matcher.group(2)+"n");}System.out.println(result.toString());System.out.println("=======开始匹配name属性值========");String patternName="(<div class="hdwiki_tmml"><a.+?)name="(.+?)">(.+?</a></div>)";pattern=Pattern.compile(patternName);matcher=pattern.matcher(source);result=result.delete(0, result.length());while(matcher.find()){result.append(matcher.group(2)+"n");}System.out.println(result.toString());}全当复习一次了!