常 量 | 等效的嵌入标志表达式 |
Pattern.CANON_EQ | 无 |
Pattern.CASE_INSENSITIVE | (?i) |
Pattern.COMMENTS | (?x) |
Pattern.MULTILINE | (?m) |
Pattern.DOTALL | (?s) |
Pattern.LITERAL | 无 |
Pattern.UNICODE_CASE | (?u) |
Pattern.UNIX_LINES | (?d) |
上表是java中的正则处理选项几个开关值。可以在使用Pattern类时使用表左侧的选项打开,也可以在使用右侧的嵌入方式,只要在正则表达式的开头加上上表的嵌入标志。
以去掉java文件中的注释为例:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.util.regex.Pattern;
/**
* 删除本类的多行及单行注释
* @author daimojingdeyu
*/
public class CommentDelete {
public static void main(String[] args) throws IOException
{
File file = new File("src/CommentDelete.java");
FileChannel channel = new FileInputStream(file).getChannel();
MappedByteBuffer mb = channel.map(MapMode.READ_ONLY, 0, file.length());
Charset ascii = Charset.forName("GBK");
CharBuffer cb = ascii.decode(mb);
// 方式1:使用Pattern.DOTALL|Pattern.MULTILINE打开单行模式和多行模式开关
// Pattern p = Pattern.compile("/\\*.*?\\*/|^\\s*//.*?$", Pattern.DOTALL|Pattern.MULTILINE);
// 方式2:使用内嵌的(?ms)打开单行和多行模式
Pattern p = Pattern.compile("(?ms)/\\*.*?\\*/|^\\s*//.*?$");
// 将注释替换成""
String presult = p.matcher(cb).replaceAll("");
System.out.println(presult);
}
}
方式1和方式2的代码分别使用了Pattern的标记和内嵌的标记完成对注释的匹配。
另外,最近搞了一下对SQL文件注释的删除,可以使用下面的表达式完成,目前较好用的,可以删除掉SQL文件中的
/*...*/的多行注释,和以 -- 开始的单行注释
Pattern p = Pattern.compile("(?ms)('(?:''|[^'])*')|--.*?$|/\\*.*?\\*/");
String presult = p.matcher(sqlString).replaceAll("$1");