日期:2014-05-18  浏览次数:20689 次

有关正则表达式的一个问题
我想把一个text文件转成xml文件,现在text文件已经存如一个String类变量里。
比如text里写
title:aaa
item:
date:bbb
content:abc
item:
date:ccc
我想把它转成
<title> aaa </title>
<item>
<date> bbb </date>
<content> abc </content>
</item>
<item>
<date> ccc </date>
</item>
用String类的replaceAll方法,如何写?谢谢

------解决方案--------------------
存在多层嵌套并且分割符一致,用正则表达式的懒惰和贪婪都无法达到
this is 我的个人意见
------解决方案--------------------
随便写了一点,仅供参考,对与不对,我不负责。

public class TestDy{

public static void main(String[] args) {

TestDy tf=new TestDy();
String str=tf.mread( "E:/test.txt ");
str=str.replaceAll( "title:(.+) ", " <title> $1 </title> ");
str=str.replaceAll( "date:(.+) ", " <date> $1 </date> ");
str=str.replaceAll( "content:(.+) ", " <content> $1 </content> ");
str=str.replaceAll( "item: ", " </item> \n <item> ");
str=str.replaceFirst( " </item> ", " ");
str=str+ " </item> ";
System.out.println(str);
}

//读文件
public String read(String path){
InputStreamReader in;
char []ch=new char[1024];
StringBuffer cb=new StringBuffer();
try {
in=new InputStreamReader(new FileInputStream(path), "UTF-8 ");
int len=0;
while((len=in.read(ch))!=-1){
cb.append(ch,0,len);
}
} catch (Exception e) {
e.printStackTrace();
}
return cb.toString();
}
}