All Downloads are FREE. Search and download functionalities are using the official Maven repository.

querqy.rewrite.contrib.replace.WildcardReplaceInstruction Maven / Gradle / Ivy

There is a newer version: 3.18.1
Show newest version
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 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)));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy