正则啊,不会,不过有一个思路
在map中存储 ${name} 然后用 string.replaceAll(key,value),应该不会太慢吧本来想用 common 中的 substringBetween的, 不过少了个 replace样的

解决方案 »

  1.   

    不难。下边是简单的参考代码。
    但请楼主注意:考虑到String的不变性,真正在项目中使用时,应该使用StringBuffer来完成替换操作。这点就留给楼主自己啦,呵呵。    public static void main(String args[]) {
         Map<String,String> values = new HashMap<String,String>();
         values.put("name", "***");
         values.put("age", "**");
         //
         String template = "我是${name},我今年${age},${abc}男";
         String regex = "[$][{]([^}]*)[}]";
         Pattern p = Pattern.compile( regex );
         Matcher m = p.matcher( template );
         String value;
         while( m.find() )
         {
         value = values.get( m.group(1) );
         if( value == null )
         value = "";
         template = template.replace( m.group(), value );
         }
         System.out.println( template );
        }
      

  2.   

    [接2楼]
    上边的代码是可以实现功能的,但性能方面还有点缺陷。
    一会得去考试,所以先这样简单写一下。
    如果楼主对StringBuffer的使用还有疑问,尽管说话。
    等我考完试,再给楼主个满意的答复。
      

  3.   

    String regex = "[$][{]([^}]*)[}]";
            Pattern p = Pattern.compile( regex );
            Matcher m = p.matcher( template );用Velocity就几行代码吧,呵呵
      

  4.   


    [2]楼正解!~!
    只需要用几行正则就可以了
    String regex = "[$][{]([^}]*)[}]"; 
    Pattern p = Pattern.compile( regex ); 
    Matcher m = p.matcher( template ); 
      

  5.   

    [接3楼]
    考完试了,心情很好。嘿嘿。送上完善之后的代码:    public static void main(String args[]) {
         Map<String,String> values = new HashMap<String,String>();
         values.put("name", "***");
         values.put("age", "**");
         //
         String template = "我是${name},我今年${age},${abc}男";
         String regex = "[$][{]([^}]*)[}]";
         Pattern p = Pattern.compile( regex );
         Matcher m = p.matcher( template );
        
         StringBuffer buffer = new StringBuffer();
         String value;
         int beginIndex = 0;
         while( m.find() )
         {
         value = values.get( m.group(1) );
         if( value == null )
         value = "";
         buffer.append( template.substring( beginIndex, m.start() ) );
         buffer.append( value );
         beginIndex = m.end();
         }
         buffer.append( template.substring( beginIndex ) );
         System.out.println( buffer );
        }
      

  6.   

    上面给出的代码正解。
    不过,从你想要的代码来看,其实你想要的是实现一种模板替换的功能。比如做代码机。建议学习下freeer,一种标准的模板语言,Velocity也可以,不过楼主最好学一种,呵呵