java中解析html代码提取字符串

Html源码:
<property name="name">
projectNo
</property>
<property name="property">
projectNo
</property>
<property name="label">
项目编号
</property>
<editor />
获取上面代码中的“项目编号”

使用正则表达式:
pattern = Pattern.compile("[\\s\\S]*?name=\"label\">[\\s\\S]*?(.*?)[\\S\\s]*?</property>[\\s\\S]*?");
System .out.println(matcher.matches());
System .out.println(matcher.group(1));
返回True,但是matcher.group(1)中无内容。请问上面的正则表达式哪里有问题。

package test;

public class JButtonTest
{
public static void main ( String[] args )
{
String regex = "[\\s\\S]+\\<property\\s+name[\\=\'\"]+label[^\\>]+\\>([^\\<]+)\\<\\/property\\>[\\s\\S]*";
String input = "<property name=\"name\">\r\nprojectNo\r\n</property>\r\n<property name=\"property\">\r\n projectNo\r\n</property>\r\n<property name=\"label\">\r\n 项目编号\r\n</property>\r\n<editor />";
System.out.println (input.replaceAll (regex, "$1"));
}
}

温馨提示:内容为网友见解,仅供参考
第1个回答  2015-01-14
Java代码  
iv=(ImageView)this.findViewById(R.id.iv);  
            iv.setTag("toRight");  
            iv.setOnClickListener(listener);  
            ani_0 = new TranslateAnimation(  
                    Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f,  
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);  
            ani_1= new TranslateAnimation(  
                    Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f,  
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);  
            ani_0.setInterpolator(new AccelerateDecelerateInterpolator());     
            ani_0.setDuration(1000);  
            ani_0.setFillEnabled(true);  
            ani_0.setFillAfter(true);  
            ani_0.setAnimationListener(animationListener);  
            ani_1.setInterpolator(new AccelerateDecelerateInterpolator());     
            ani_1.setDuration(1000);  
            ani_1.setFillEnabled(true);  
            ani_1.setFillAfter(true);

第2个回答  2015-01-14

你好:

正则可以这样写

pattern = Pattern.compile("[\\s\\S]*?name=\"label\">(.*?)</property>[\\s\\S]*?");

追问

你好,我用了你写的正则表达式,matcher.matches()返回的是false。

追答

根据你的写的,

String string = "<property name=\"label\">项目编号</property><editor />";
Pattern p = null;
p = Pattern.compile("[\\s\\S]*?name=\"label\">(.*?)</property>[\\s\\S]*?");
Matcher m = p.matcher(string);
while(m.find()){
System.out.println("string="+m.group(1));
}
System.out.println(m.matches());

结果:

string=项目编号

true

追问

恩,我把单独的项目编号提取出来放在一个String中,使用你的正则表达式是可以的,但是放在字符串中:
...

项目编号

...
就是错误的

第3个回答  2015-01-14
转成xml就简单多了。
相似回答