1
14
15 package com.liferay.portal.kernel.util;
16
17 import java.util.regex.MatchResult;
18 import java.util.regex.Matcher;
19 import java.util.regex.Pattern;
20
21
30 public class CallbackMatcher {
31
32 public String replaceMatches(CharSequence charSequence, Callback callback) {
33 Matcher matcher = _pattern.matcher(charSequence);
34
35 StringBuilder sb = new StringBuilder(charSequence);
36
37 int offset = 0;
38
39 while (matcher.find()) {
40 MatchResult matchResult = matcher.toMatchResult();
41
42 String replacement = callback.foundMatch(matchResult);
43
44 int matchStart = offset + matchResult.start();
45 int matchEnd = offset + matchResult.end();
46
47 sb.replace(matchStart, matchEnd, replacement);
48
49 int matchLength = matchResult.end() - matchResult.start();
50 int lengthChange = replacement.length() - matchLength;
51
52 offset += lengthChange;
53 }
54
55 return sb.toString();
56 }
57
58 public void setRegex(String regex) {
59 _pattern = Pattern.compile(regex);
60 }
61
62 public interface Callback {
63
64 public String foundMatch(MatchResult matchResult);
65
66 }
67
68 private Pattern _pattern;
69
70 }