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

io.cucumber.cucumberexpressions.RegularExpression Maven / Gradle / Ivy

There is a newer version: 17.1.0
Show newest version
package io.cucumber.cucumberexpressions;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpression implements Expression {
    private static final Pattern CAPTURE_GROUP_PATTERN = Pattern.compile("\\((?!\\?:)([^(]+)\\)");

    private final Pattern expressionRegexp;
    private final ParameterTypeRegistry parameterTypeRegistry;
    private TreeRegexp treeRegexp;

    /**
     * Creates a new instance. Use this when the transform types are not known in advance,
     * and should be determined by the regular expression's capture groups. Use this with
     * dynamically typed languages.
     *
     * @param expressionRegexp      the regular expression to use
     * @param parameterTypeRegistry used to look up parameter types
     */
    public RegularExpression(Pattern expressionRegexp, ParameterTypeRegistry parameterTypeRegistry) {
        this.expressionRegexp = expressionRegexp;
        this.parameterTypeRegistry = parameterTypeRegistry;
        treeRegexp = new TreeRegexp(expressionRegexp);
    }

    @Override
    public List> match(String text) {
        List> parameterTypes = new ArrayList<>();

        Matcher matcher = CAPTURE_GROUP_PATTERN.matcher(expressionRegexp.pattern());
        while (matcher.find()) {
            String parameterTypeRegexp = matcher.group(1);

            ParameterType parameterType = parameterTypeRegistry.lookupByRegexp(parameterTypeRegexp, expressionRegexp, text);
            if (parameterType == null) {
                parameterType = new ParameterType<>(
                        parameterTypeRegexp,
                        parameterTypeRegexp,
                        String.class,
                        new SingleTransformer<>(String::new)
                );
            }
            parameterTypes.add(parameterType);
        }
        return Argument.build(treeRegexp, parameterTypes, text);
    }


    @Override
    public Pattern getRegexp() {
        return expressionRegexp;
    }

    @Override
    public String getSource() {
        return expressionRegexp.pattern();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy