寫道
str="/* */ package cn.ehoo.dao;";
System.out.println(str.replaceAll("/\\*.+\\*/", "");
意思是把 str 裡的/* */用空格給替換掉。
結果就是 package cn.ehoo.dao; 而不會再有 /* */
另一個方法是用到java提供的兩個類,一個是Matcher,一個是Pattern。
Java代碼
File path = new File("d:\\DAOSupport.java");
FileInputStream fis = new FileInputStream(path);
byte[] b = new byte[(int) path.length()];
int len = fis.read(b);
String str = new String(b, 0, len, "UTF-8");
str="/* */ package cn.ehoo.dao;";
// System.out.println(str.replaceAll("/\\*.+\\*/", ""));
Pattern pattern = Pattern.compile("/\\*.+\\*/");//用指定的正則表達式進行預編譯
Matcher matcher = pattern.matcher(str);//創建匹配給定輸入與此模式的匹配器。
StringBuffer sbf = new StringBuffer();
while (matcher.find()) {//描輸入序列以查找與該模式匹配的下一個子序列。
//System.out.println(sbf.toString());
matcher.appendReplacement(sbf, "");//
}
matcher.appendTail(sbf);
System.out.println(sbf.toString());