querqy.rewrite.contrib.replace.WildcardReplaceInstruction Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of querqy-core Show documentation
Show all versions of querqy-core Show documentation
Querqy library for query rewriting: Querqy Core
package querqy.rewrite.contrib.replace;
import querqy.CompoundCharSequence;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.IntStream;
public class WildcardReplaceInstruction implements ReplaceInstruction {
@FunctionalInterface
public interface TermCreator {
CharSequence createTerm(final CharSequence wildcardMatch);
}
private final List termCreators = new LinkedList<>();
public WildcardReplaceInstruction(final List extends CharSequence> replacementTerms) {
replacementTerms.stream()
.map(CharSequence::toString)
.forEach(replacementTerm -> {
final int indexWildcardReplacement = replacementTerm.indexOf("$1");
if (indexWildcardReplacement < 0) {
termCreators.add(0, wildcardMatch -> replacementTerm);
} else {
final String leftPart = replacementTerm.substring(0, indexWildcardReplacement);
final String rightPart = replacementTerm.substring(indexWildcardReplacement + 2);
termCreators.add(0, wildcardMatch ->
new CompoundCharSequence(null, leftPart, wildcardMatch, rightPart));
}
});
}
@Override
public void apply(final List seq,
final int start,
final int exclusiveOffset,
final CharSequence wildcardMatch) {
IntStream.range(0, exclusiveOffset).forEach(i -> seq.remove(start));
termCreators.forEach(termCreator -> seq.add(start, termCreator.createTerm(wildcardMatch)));
}
}