【发布时间】:2012-01-05 10:32:18
【问题描述】:
下面提到的 RegEx 在非常大的字符串或超过 2000 行的情况下表现很差。基本上,Java 字符串由 PL/SQL 脚本组成。
1- 用字符前后的空格替换每次出现的定界字符,例如 ||、!= 或 > 符号。这需要无限的时间并且永远不会结束,因此无法记录时间。
// Delimiting characters for SQLPlus
private static final String[] delimiters = { "\\|\\|", "=>", ":=", "!=", "<>", "<", ">", "\\(", "\\)", "!", ",", "\\+", "-", "=", "\\*", "\\|" };
for (int i = 0; i < delimiters.length; i++) {
script = script.replaceAll(delimiters[i], " " + delimiters[i] + " ");
}
2- 以下模式查找所有出现的正斜杠 / 除了前面带有 * 的那些。这意味着不要在块注释语法中寻找正斜杠。 2000 行字符串大约需要 103 秒。
Pattern p = Pattern.compile("([^\\*])([\\/])([^\\*])");
Matcher m = p.matcher(script);
while (m.find()) {
script = script.replaceAll(m.group(2), " " + m.group(2) + " ");
}
3- 从日期或日期格式中删除任何空格
Pattern p = Pattern.compile("(?i)(\\w{1,2}) +/ +(\\w{1,2}) +/ +(\\w{2,4})");
// Create a matcher with an input string
Matcher m = p.matcher(script);
while (m.find()) {
part1 = script.substring(0, m.start());
part2 = script.substring(m.end());
script = part1 + m.group().replaceAll("[ \t]+", "") + part2;
m = p.matcher(script);
}
有什么方法可以优化所有三个 RegEx 以减少它们花费的时间?
谢谢
阿里
【问题讨论】:
-
你应该把这个问题分成三个独立的问题。这也将帮助您创建比“优化多个正则表达式”更有意义(因此也很有趣)的问题标题...
标签: java regex optimization