ivaneeo's blog

自由的力量,自由的生活。

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  669 Posts :: 0 Stories :: 64 Comments :: 0 Trackbacks
我有这样一句sql语句:select ${ 0},${ 1},${2 },${2 } from t where ${0}='${2}'。

我的目的是先找出所有的变量,并把变量的值替换为: V变量名。

        String statement = "select ${ 0},${ 1},${2 },${2 } from t where ${0}='${2}'";
        System.out.println(statement);
        Matcher m = Pattern.compile("(\\$\\{\\s*(\\d+)\\s*\\})").matcher(statement);
        StringBuffer buffer = new StringBuffer();
        while(m.find()) {
            System.out.println("Matched:'" + m.group(1) + "' at position " + m.start());
            System.out.println("Matched:'" + m.group(2) + "' at position " + m.start());
            int temp = Integer.parseInt(m.group(2));
            if(temp == 0)
                m.appendReplacement(buffer, "V0");
            else if(temp == 1)
                m.appendReplacement(buffer, "V1");
            else if(temp == 2)
                m.appendReplacement(buffer, "V2");
        }
        m.appendTail(buffer);
        System.out.println(buffer.toString());

输出结果:
select ${ 0},${ 1},${2 },${2 } from t where ${0}='${2}'
Matched:'${ 0}' at position 7
Matched:'0' at position 7
Matched:'${ 1}' at position 13
Matched:'1' at position 13
Matched:'${2 }' at position 19
Matched:'2' at position 19
Matched:'${2 }' at position 25
Matched:'2' at position 25
Matched:'${0}' at position 44
Matched:'0' at position 44
Matched:'${2}' at position 50
Matched:'2' at position 50
select V0,V1,V2,V2 from t where V0='V2'

这里要逐个替换就要使用类Matcher的appendReplacement()和appendTail()方法。
posted on 2005-09-12 13:31 ivaneeo 阅读(458) 评论(0)  编辑  收藏 所属分类: java魔力

只有注册用户登录后才能发表评论。


网站导航: