View Javadoc

1   package com.atlassian.plugin.webresource.transformer;
2   
3   import com.google.common.base.Function;
4   
5   import java.util.regex.Matcher;
6   import java.util.regex.Pattern;
7   
8   /**
9    * Performs a search and replace function on a given input.
10   * @since 2.9.0
11   */
12  public class SearchAndReplacer
13  {
14      public static SearchAndReplacer create(final Pattern pattern, final Function<Matcher, CharSequence> replacer)
15      {
16          return new SearchAndReplacer(pattern, replacer);
17      }
18  
19      private final Pattern pattern;
20      private final Function<Matcher, CharSequence> replacer;
21  
22      /**
23       * @param pattern the pattern to find in the input
24       * @param replacer a function that gives replacement text for the given match
25       */
26      SearchAndReplacer(final Pattern pattern, final Function<Matcher, CharSequence> replacer)
27      {
28          this.pattern = pattern;
29          this.replacer = replacer;
30      }
31  
32      /**
33       * Replace all occurrences of the pattern in the input, using the given function
34       */
35      public CharSequence replaceAll(final CharSequence input)
36      {
37          final Matcher matcher = pattern.matcher(input);
38          final StringBuffer output = new StringBuffer();
39          while (matcher.find())
40          {
41              final CharSequence sequence = replacer.apply(matcher);
42              matcher.appendReplacement(output, "");
43              output.append(sequence);
44          }
45          matcher.appendTail(output);
46          return output;
47      }
48  }