Skip to content

Commit feca863

Browse files
authored
Update CucumberExpression.java
Refactored `escapeRegex` with ~7 times performance improvement.
1 parent cd417de commit feca863

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

java/src/main/java/io/cucumber/cucumberexpressions/CucumberExpression.java

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,27 @@
2424

2525
@API(status = API.Status.STABLE)
2626
public final class CucumberExpression implements Expression {
27-
private static final Pattern ESCAPE_PATTERN = Pattern.compile("[\\\\^\\[({$.|?*+})\\]]");
28-
27+
/**
28+
* List of characters to be escaped.
29+
* The last char is '}' with index 125, so we need only 126 characters.
30+
*/
31+
private static final boolean[] CHAR_TO_ESCAPE = new boolean[126];
32+
static {
33+
CHAR_TO_ESCAPE['^'] = true;
34+
CHAR_TO_ESCAPE['$'] = true;
35+
CHAR_TO_ESCAPE['['] = true;
36+
CHAR_TO_ESCAPE[']'] = true;
37+
CHAR_TO_ESCAPE['('] = true;
38+
CHAR_TO_ESCAPE[')'] = true;
39+
CHAR_TO_ESCAPE['{'] = true;
40+
CHAR_TO_ESCAPE['}'] = true;
41+
CHAR_TO_ESCAPE['.'] = true;
42+
CHAR_TO_ESCAPE['|'] = true;
43+
CHAR_TO_ESCAPE['?'] = true;
44+
CHAR_TO_ESCAPE['*'] = true;
45+
CHAR_TO_ESCAPE['+'] = true;
46+
CHAR_TO_ESCAPE['\\'] = true;
47+
}
2948
private final List<ParameterType<?>> parameterTypes = new ArrayList<>();
3049
private final String source;
3150
private final TreeRegexp treeRegexp;
@@ -62,7 +81,17 @@ private String rewriteToRegex(Node node) {
6281
}
6382

6483
private static String escapeRegex(String text) {
65-
return ESCAPE_PATTERN.matcher(text).replaceAll("\\\\$0");
84+
int length = text.length();
85+
StringBuilder sb = new StringBuilder(length * 2); // prevent resizes
86+
int maxChar = CHAR_TO_ESCAPE.length;
87+
for (int i = 0; i < length; i++) {
88+
char currentChar = text.charAt(i);
89+
if (currentChar < maxChar && CHAR_TO_ESCAPE[currentChar]) {
90+
sb.append('\\');
91+
}
92+
sb.append(currentChar);
93+
}
94+
return sb.toString();
6695
}
6796

6897
private String rewriteOptional(Node node) {

0 commit comments

Comments
 (0)