日期:2014-05-20  浏览次数:20767 次

求助:java正则替换字符串问题
<root id='tt'><![CDATA[111 3333]]><root> <basisInfo><![CDATA[111 3333]]>

我想把<![CDATA 标签里的空格替换成&nbsp;应该怎么写呀,有高手没

另:CSDN改版后怎么变的这么慢??

------解决方案--------------------
不明白标签是什么 所以不太清楚楼主的要求

是不是 转后变成这个效果:
<root id= 'tt ' > <![CDATA[111&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3333]]&nbsp;> <root > <basisInfo > <![CDATA[111&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3333]]&nbsp;>


是的话 我的代码是:
public class StrC {

public static String str=
"<root id= 'tt ' > <![CDATA[111 3333]] > <root > <basisInfo > <![CDATA[111 3333]] >";

public String chang(String str, String start, String end, String s1, String s2)
{
int len1=0,len2=0;
do{
len1=str.indexOf("<![CDATA",len2);
if (len1!=-1)
{
len2=str.indexOf(">",len1);
String temp=str.substring(len1,len2);
temp=temp.replaceAll(s1,s2);
str=str.substring(0,len1)+temp+str.substring(len2);
}
} while (len1!=-1);

return str;
}

public static void main(String[] args)
{
StrC sc=new StrC();
String result=sc.chang(str,"<![CDATA",">"," ","&nbsp;");
System.out.println(result);
}
}
------解决方案--------------------
Java code
        String str = "<root id= 'tt ' > <![CDATA[111      3333]] > <root >" +
                "          <basisInfo > <![CDATA[222      4444]] > ";
        
        Pattern p = Pattern.compile("(.*?<\\!\\[CDATA)(.*?\\] >)");
        Matcher m = p.matcher(str);
        
        String rtn ="";
        while(m.find()){
            rtn += m.group(1) + 
                m.group(2).replaceAll("\\s", "&nbsp;");
        }
        System.out.println(rtn);