private static String replaceAll ( String source , String search , String replace ) { if ( USE_REPLACE_ALL ) { return source . replaceAll ( search , replace ) ; } else { Pattern p = Pattern . compile ( search ) ; Matcher m = p . matcher ( source ) ; StringBuffer sb = new StringBuffer ( ) ; boolean atLeastOneFound = false ; while ( m . find ( ) ) { m . appendReplacement ( sb , replace ) ; atLeastOneFound = true ; } if ( atLeastOneFound ) { m . appendTail ( sb ) ; return sb . toString ( ) ; } else { return source ; } } }
A memory optimized algorithm for String . replaceAll