Alternative to successive String.replace

后端 未结 7 1056
無奈伤痛
無奈伤痛 2020-12-14 07:10

I want to replace some strings in a String input :

string=string.replace(\"

\",\"\"); string=string.replac

7条回答
  •  攒了一身酷
    2020-12-14 07:44

    Unfortunately StringBuilder doesn't provide a replace(string,string) method, so you might want to consider using Pattern and Matcher in conjunction with StringBuffer:

    String input = ...;
    StringBuffer sb = new StringBuffer();
    
    Pattern p = Pattern.compile("");
    Matcher m = p.matcher( input );
    while( m.find() )
    {
      String match = m.group();
      String replacement = ...; //get replacement for match, e.g. by lookup in a map
    
      m.appendReplacement( sb, replacement );
    }
    m.appendTail( sb );
    

    You could do something similar with StringBuilder but in that case you'd have to implement appendReplacement etc. yourself.

    As for the expression you could also just try and match any html tag (although that might cause problems since regex and arbitrary html don't fit very well) and when the lookup doesn't have any result you just replace the match with itself.

提交回复
热议问题