/** * Perform a search replace on a text. * Takes into account special caracters. * * @param text the text to work on - must not be null. * @param patternStr the string to look for - must not be null. * @param replacement the replacement string - must not be null. * @return the modified String */ public static String replace ( String text, String patternStr, String replacement ) { if ( text == null ) throw new IllegalArgumentException( "The text you want to modify must not be null!" ); if ( patternStr == null ) throw new IllegalArgumentException( "The pattern you want to replace must not be null!" ); if ( replacement == null ) throw new IllegalArgumentException( "The replacement string must not be null!" ); String escapedPatternStr = escapeRE( patternStr ); // Compile regular expression Pattern pattern = Pattern.compile (escapedPatternStr); // Replace all occurrences of pattern in input Matcher matcher = pattern.matcher (text); String result = matcher.replaceAll (replacement); return result; } }
/** * Perform a search replace on a text. * Takes into account special caracters. * * @param text the text to work on - must not be null. * @param patternStr the string to look for - must not be null. * @param replacement the replacement string - must not be null. * @return the modified String */ public static String replace ( String text, String patternStr, String replacement ) { if ( text == null ) throw new IllegalArgumentException( "The text you want to modify must not be null!" ); if ( patternStr == null ) throw new IllegalArgumentException( "The pattern you want to replace must not be null!" ); if ( replacement == null ) throw new IllegalArgumentException( "The replacement string must not be null!" ); String escapedPatternStr = escapeRE( patternStr ); // Compile regular expression Pattern pattern = Pattern.compile (escapedPatternStr); // Replace all occurrences of pattern in input Matcher matcher = pattern.matcher (text); String result = matcher.replaceAll (replacement); return result; } }