Skip to content

Commit 7412c71

Browse files
committed
Fix sanitize() & modifier bugs and add test() & testExact()
- Add test and testExact methods. test searches for regex match within string, testExact tests whole string against regex. - Fix bug where test and testExact would compile patterns without modifiers - Fix sanitize to not use Pattern.quote as it causes it to add \Q & \E causing errors
1 parent 6b260cc commit 7412c71

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

src/main/java/VerbalExpression.java

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import java.util.regex.Pattern;
2+
import java.util.regex.Matcher;
23

34
class VerbalExpression {
45
private String prefixes = "", source = "", suffixes = "", pattern = "";
@@ -9,9 +10,19 @@ public VerbalExpression () {
910
}
1011

1112
private String sanitize(String value) {
12-
if(value == null)
13-
return value;
14-
return Pattern.quote(value);
13+
Matcher matcher = Pattern.compile("").matcher("").usePattern(Pattern.compile("[^\\w]"));
14+
int lastEnd = 0;
15+
String result = "";
16+
matcher.reset(value);
17+
boolean matcherCalled = false;
18+
while (matcher.find()) {
19+
matcherCalled = true;
20+
if (matcher.start() != lastEnd) result += value.substring(lastEnd, matcher.start());
21+
result += "\\" + value.substring(matcher.start(), matcher.end());
22+
lastEnd = matcher.end();
23+
}
24+
if (!matcherCalled) return value;
25+
return result;
1526
}
1627

1728
public VerbalExpression add(String value) {
@@ -240,8 +251,12 @@ public VerbalExpression or(String value) {
240251
return this;
241252
}
242253

254+
public boolean testExact(String toTest) {
255+
return Pattern.compile(this.pattern, this.modifiers).matcher(toTest).matches();
256+
}
257+
243258
public boolean test(String toTest) {
244-
return Pattern.matches(this.pattern, toTest);
259+
return Pattern.compile(this.pattern, this.modifiers).matcher(toTest).find();
245260
}
246261

247262
public String toString() {

0 commit comments

Comments
 (0)