Last active
August 29, 2015 14:26
-
-
Save decebals/56759f2074031a56f76f to your computer and use it in GitHub Desktop.
An utility class that help me to create complex regex paths using only includes and excludes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 + | |
'}'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use (snippet from my
PIppoApplication.java
):