001
014
015 package com.liferay.portal.kernel.util;
016
017 import java.util.regex.MatchResult;
018 import java.util.regex.Matcher;
019 import java.util.regex.Pattern;
020
021
028 public class CallbackMatcher {
029
030 public String replaceMatches(CharSequence charSequence, Callback callback) {
031 Matcher matcher = _pattern.matcher(charSequence);
032
033 StringBuilder sb = new StringBuilder(charSequence);
034
035 int offset = 0;
036
037 while (matcher.find()) {
038 MatchResult matchResult = matcher.toMatchResult();
039
040 String replacement = callback.foundMatch(matchResult);
041
042 int matchStart = offset + matchResult.start();
043 int matchEnd = offset + matchResult.end();
044
045 sb.replace(matchStart, matchEnd, replacement);
046
047 int matchLength = matchResult.end() - matchResult.start();
048 int lengthChange = replacement.length() - matchLength;
049
050 offset += lengthChange;
051 }
052
053 return sb.toString();
054 }
055
056 public void setRegex(String regex) {
057 _pattern = Pattern.compile(regex);
058 }
059
060 public interface Callback {
061
062 public String foundMatch(MatchResult matchResult);
063
064 }
065
066 private Pattern _pattern;
067
068 }