Java正则替换一例
不区分大小写,换行支持。。。,一个SQL工具要用这个代码。
package com.lavasoft.regtest;
import Java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 正则表达式SQL工具
*
* @author leizhimin 2010-5-18 10:34:34
*/
public class RegexToolkit {
// private static final Pattern p_wellsql = Pattern.compile("\\s+?where\\s*?and\\s+?", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private static final Pattern p_wellsql = Pattern.compile("(?i)(?m)\\s+?where\\s*?and\\s+?");
public static String genWellSQL(String badSQL) {
Matcher m = p_wellsql.matcher(badSQL);
return m.replaceAll(" where ");
}
public static void main(String[] args) {
String badsql = "select x.subs_level_id, count(x.logdataid)\n" +
" from (select a.*\n" +
" from qm_subject_mining a\n" +
"\t Where \n" +
"\t aND a.orgid = 901\n" +
" order by a.subs_level_id, a.usersatisfy, a.callstarttime desc) x\n" +
" WHere And rownum <= 30\n" +
" group by subs_level_id;";
String wellsql = genWellSQL(badsql);
System.out.println("替换前SQL:\n" + badsql);
System.out.println("替换后SQL:\n" + wellsql);
}
}
运行结果:
替换前SQL:
select x.subs_level_id, count(x.logdataid)
from (select a.*
from qm_subject_mining a
Where
aND a.orgid = 901
order by a.subs_level_id, a.usersatisfy, a.callstarttime desc) x
WHere And rownum <= 30
group by subs_level_id;
替换后SQL:
select x.subs_level_id, count(x.logdataid)
from (select a.*
from qm_subject_mining a where a.orgid = 901
order by a.subs_level_id, a.usersatisfy, a.callstarttime desc) x where rownum <= 30
group by subs_level_id;
Process finished with exit code 0
注意:一下两行代码是等价的。
private static final Pattern p_wellsql = Pattern.compile("\\s+?where\\s*?and\\s+?", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private static final Pattern p_wellsql = Pattern.compile("(?i)(?m)\\s+?where\\s*?and\\s+?");