01: package com.opensymphony.module.sitemesh.html.rules;
02:
03: import com.opensymphony.module.sitemesh.html.TextFilter;
04:
05: import java.util.regex.Pattern;
06: import java.util.regex.Matcher;
07:
08: /**
09: * TextFilter that substitutes content using a JDK 1.4 regular expression.
10: *
11: * <h3>Example</h3>
12: *
13: * This will substitute 'Google:Blah' for a link to a google search.
14: *
15: * <pre>HTMLProcessor processor = new HTMLProcessor(in, out);
16: * processor.addTextFilter(new RegexReplacementTextFilter("Google:([a-zA-Z]+)", "<a href='http://www.google.com/q=$1'>$1</a>"));
17: * // add more TextFilters and TagRules
18: * processor.process();</pre>
19: *
20: * @author Joe Walnes
21: */
22: public class RegexReplacementTextFilter implements TextFilter {
23:
24: private final Pattern regex;
25: private final String replacement;
26:
27: public RegexReplacementTextFilter(String regex, String replacement) {
28: this .regex = Pattern.compile(regex);
29: this .replacement = replacement;
30: }
31:
32: public RegexReplacementTextFilter(Pattern regex, String replacement) {
33: this .regex = regex;
34: this .replacement = replacement;
35: }
36:
37: public String filter(String text) {
38: Matcher matcher = regex.matcher(text);
39: return matcher.replaceAll(replacement);
40: }
41:
42: }
|