java 一个实用程序类,它帮助我仅使用包含和排除来创建复杂的正则表达式路径。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 一个实用程序类,它帮助我仅使用包含和排除来创建复杂的正则表达式路径。相关的知识,希望对你有一定的参考价值。

package ro.fortsoft.matilda.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Decebal Suiu
 */
public class PathRegexBuilder {

    private List<String> includes;
    private List<String> excludes;

    public PathRegexBuilder() {
        includes = new ArrayList<>();
        excludes = new ArrayList<>();
    }

    public PathRegexBuilder includes(String... includes) {
        this.includes.addAll(Arrays.asList(includes));

        return this;
    }

    public PathRegexBuilder excludes(String... excludes) {
        this.excludes.addAll(Arrays.asList(excludes));

        return this;
    }

    public String build() {
        StringBuilder regex = new StringBuilder();

        // add includes
        StringBuilder regexIncludes = new StringBuilder();
        if (!includes.isEmpty()) {
            regexIncludes.append('^'); // the beginning of a line
            regexIncludes.append('(');
            for (String include : includes) {
                regexIncludes.append(include);
                regexIncludes.append('|'); // or
            }
            regexIncludes.deleteCharAt(regexIncludes.length() - 1);
            regexIncludes.append(").*");
        }

        if (!excludes.isEmpty()) {

        }

        // add excludes
        StringBuilder regexExcludes = new StringBuilder();
        if (!excludes.isEmpty()) {
            regexExcludes.append('^'); // the beginning of a line
            regexExcludes.append("(?!"); // zero-width negative lookahead
            for (String exclude : excludes) {
                regexExcludes.append(exclude);
                regexExcludes.append('|'); // or
            }
            regexExcludes.deleteCharAt(regexExcludes.length() - 1);
            regexExcludes.append(").+");
        }

        if (regexIncludes.length() == 0) {
            regex.append(regexExcludes);
        } else {
            if (regexExcludes.length() == 0) {
                regex.append(regexIncludes);
            } else {
                regex.append("(?=");
                regex.append(regexIncludes);
                regex.append(')');
                regex.append(regexExcludes);
            }
        }

        return regex.toString();
    }

    @Override
    public String toString() {
        return "RegexBuilder{" +
            "includes=" + includes +
            ", excludes=" + excludes +
            '}';
    }

}

以上是关于java 一个实用程序类,它帮助我仅使用包含和排除来创建复杂的正则表达式路径。的主要内容,如果未能解决你的问题,请参考以下文章

实用类(Math,String及Date,Calendar)

包实用程序不存在错误

JDK 内置实用工具:监视故障排除

java 一个实用程序类,它使用各种方法来确定两个字符串之间的相似性。

JAVA集合面试问题

Java Spring Boot 测试:如何从测试上下文中排除 java 配置类