001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
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                            if (replacement == null) {
043                                    continue;
044                            }
045    
046                            int matchStart = offset + matchResult.start();
047                            int matchEnd = offset + matchResult.end();
048    
049                            sb.replace(matchStart, matchEnd, replacement);
050    
051                            int matchLength = matchResult.end() - matchResult.start();
052                            int lengthChange = replacement.length() - matchLength;
053    
054                            offset += lengthChange;
055                    }
056    
057                    return sb.toString();
058            }
059    
060            public void setRegex(String regex) {
061                    _pattern = Pattern.compile(regex);
062            }
063    
064            public interface Callback {
065    
066                    public String foundMatch(MatchResult matchResult);
067    
068            }
069    
070            private Pattern _pattern;
071    
072    }