如果有一个字符串里面包含[@01]....[@02]....[@05]  需要把[@01][@02][@05]分别对应里面的数字内容替换成为2001,2002,2005的话,并且这里面的这种参数的个数是不固定的。有啥简便的写法啊?请高手提示。
我现在想到的办法只有通过@来判断参数的个数,然后用这个个数做一个循环,用indexOf和substring来挨个把里面参数替换,但是这样觉得很麻烦还有更简便的方法吗?

解决方案 »

  1.   


    final String s = "[@01]....[@02]....[@05]";
    System.out.println(s.replaceAll("(\\[@)(\\d+\\])", "$120$2"));
      

  2.   

    问题补充:source="[@01]....[@02]....[@05]...[@15]...[@20]" 
    可能把里面的内容分别乘2 
    可能替换成2....4....10...30...40 
      

  3.   

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class Test { public static void main(String[] args) {
    String source = "[@01]....[@02]....[@05]...[@15]...[@20]";
    String regex = "\\[@(\\d+)\\]";
    String[] arr = source.split(regex);
    int i = 0;
    String s = "";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(source);
    while (m.find()) {
    if (i < arr.length)
    s += arr[i++];
    s += replace(m.group(1));
    }
    while (i < arr.length)
    s += arr[i++];
    System.out.println(s);
    } public static String replace(String s) {
    try {
    int i = new Integer(s);
    return String.valueOf(2 * i);
    } catch (Throwable t) {
    return "";
    }
    }
    }这样?具体替换成啥在replace里改返回值
      

  4.   

    string str="[@01]....[@02]....[@05]"
    System.out.println(str.replace("@0","@200"));