1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   *
13   */
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  /**
22   * <a href="CallbackMatcher.java.html"><b><i>View Source</i></b></a>
23   *
24   * <p>
25   * See http://issues.liferay.com/browse/LPS-6872.
26   * </p>
27   *
28   * @author Jonathan Potter
29   */
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  }