有一个字符串向下面的那样
afdf{2},adf{3}dfsfdsf{5}我怎么把{2},{3},{5}等这样的字符替换成别的文字,比如hellow
最终结果:afdfhellow,adfhellowdfsfdsfhellow

解决方案 »

  1.   

    用正则表达式:
    String str ="afdf{2},adf{3}dfsfdsf{5}";
    String rStr=str.replaceAll("\\{\\d\\}", "hellow");
    System.out.println(rStr);
      

  2.   

    由于本人正则表达式学的不精,写个笨方法给你看一下。能实现你的功能。List list=new ArrayList();
    for(int i=0;i<10;i++)
    {
    list.add("{"+i+"}");
    }
    String str="afdf{2},adf{3}dfsfdsf{5}";
    for(int j=0;j<list.size();j++)

    str=str.replace(list.get(j).toString(), "hellow");

    System.out.println(str);
      

  3.   


    System.out.println("afdf{2},adf{3}dfsfdsf{5}".replaceAll("\\{\\d}", "hellow"));
      

  4.   


    这个有些还是实现不了,如当afdf{20},adf{30}dfsfdsf{50}或者比这更大的就不行,应该这样
    System.out.println("afdf{200},adf{300}dfsfdsf{500}".replaceAll("\\{\\d{1,5}}", "hellow"));我这个最大支持0-99999之间的数,如果你的需求比这个之间的数更大你可以改replaceAll("\\{\\d{1,5}}", "hellow"));