Java正则替换一例

2012-11-12

  不区分大小写,换行支持。。。,一个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+?");

  本文出自 “熔 岩” 博客,请务必保留此出处http://lavasoft.blog.51cto.com/62575/317353

分享到:
0
相关阅读
友情链接
© 2018 我考网 http://www.woexam.com 中国互联网举报中心 湘ICP备18023104号 京公网安备 11010802020116号
违法和不良信息举报:9447029@qq.com