想把String str=“abc cde 我 #$”中的词如: abc 我  #$ ,前后加上%,变成:%abc% %我%,正则表达式该怎么写?其中字符已经很规则 字与字之间只有一空格,字符串开始,结尾没有空格(trim过)

解决方案 »

  1.   

    s=s.replaceAll(" ","% %");
    s="%"+s+"%";
      

  2.   

    不对,我自己解决了。str=str.replaceAll("\\b", "%");,多谢大家。
      

  3.   

    使用appendReplacement()
    StringBuffer sbuf=new StringBuffer(str);
    Pattern p=Pattern.compile("//S+");
    Matcher m=p.Matcher(str);
    while(m.find())
        m.appendReplacement(sbuf,"%"+m.group()+"%");//没有试验%前面是否要加//,自己测试一下
    m.appendTail(sbuf);