001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
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    /**
022     * <p>
023     * See http://issues.liferay.com/browse/LPS-6872.
024     * </p>
025     *
026     * @author Jonathan Potter
027     */
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    }