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

字符串查找替换问题!
<ParaFile   name= "COMM "   type= "1 ">
<Items   name= "GROUP1 "   SetNo= "1 "
<Item   name= "ss "     dvalue= "44 "   validM= " "/>
<Item   name= "bb "     dvalue= "44 "   validM= " "/>
<Item   name= "gg "     dvalue= "44 "   validM= " "/>
</Items>
</ParaFile>

---------------------------
假设上面是一段字符串,我有3个数字1-3;
我想把1,3依次放入dvalue里面,怎么写这个程序效率最高。

返回字符串:
<ParaFile   name= "COMM "   type= "1 ">
<Items   name= "GROUP1 "   SetNo= "1 "
<Item   name= "ss "     dvalue= "1 "   validM= " "/>
<Item   name= "bb "     dvalue= "2 "   validM= " "/>
<Item   name= "gg "     dvalue= "3 "   validM= " "/>
</Items>
</ParaFile>

for   (int   i   =   0;   i   <   3;   i++)
{
    ...........
}

------解决方案--------------------
正则表达式查找替换
------解决方案--------------------
package rigex;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexTest {
/**
* <Item name= "ss " dvalue= "1 " validM= " "/>
*
*/
private static String reg = "dvalue=\ "(\\d*)\ " ";

public static void main(String[] args) {
try {
File f = new File( "D:\\1.txt ");
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;
StringBuffer sb = new StringBuffer();
int i = 1;
while ((line = br.readLine()) != null) {
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(line);
if (m.find()) {
String l = m.group(1);
line = line.replaceAll(l, String.valueOf(i));
i++;
}
sb.append(line);
}
System.out.println(sb);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}