利用正则表达式来替换文本中匹配正则的内容
今天同事的一个问题,我写了个demo,替换掉文本中的满足IP格式的字符串,替换成需要更改的。
IP格式没有严格写,简单弄个demo。这个可以演变成查询日志,替换或者标红关键字等。
对于其中的正则等java类可参看http://www.cnblogs.com/playing/archive/2011/03/15/1984943.html
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.util.regex.Matcher;import java.util.regex.Pattern;public class TestFile{static final String REGEX_IPV4 = "(\\d{1,3}\\.){3}\\d{1,3}";static final String ENCODE = "UTF-8";BufferedReader br = null;BufferedWriter bw = null;public void copyFile(String ip) throws IOException{try {Pattern pattern = Pattern.compile(REGEX_IPV4);br = new BufferedReader(new InputStreamReader(new FileInputStream("d:/A.txt"), ENCODE));bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:/B.txt")));String line = null;while ((line = br.readLine()) != null) {StringBuffer sbr = new StringBuffer();Matcher matcher = pattern.matcher(line);while (matcher.find()) {// 有字符串fatcatfatcatfat,假设既有正则表达式模式为"cat",第一次匹配后调用appendReplacement(sb,"dog"),那么这时StringBuffer// sb的内容为fatdog,也就是fatcat中的cat被替换为dog并且与匹配子串前的内容加到sb里,而第二次匹配后调用appendReplacement(sb,"dog"),那么sb的内容就变为fatdogfatdog,如果最后再调用一次appendTail(sb),那么sb最终的内容将是fatdogfatdogfat。matcher.appendReplacement(sbr, ip);}// 将最后一次匹配工作后剩余的字符串添加到一个StringBuffer对象里matcher.appendTail(sbr);bw.write(sbr.toString());bw.newLine();}} catch (IOException e) {} finally {bw.close();br.close();}}public static void main(String[] args) throws IOException{new TestFile().copyFile("255.255.255.0");}}