Skip to content

Commit

Permalink
reject assertions in groups, ignore non-capturing groups
Browse files Browse the repository at this point in the history
When parsing, reject lookahead/behind assertions
(?!...) (?=...) (?<!...) (?<=...)
As well as named capture groups
(?<stuff>...)

Additionally, non-capturing groups are parsed-correctly
(?:...) ==> (...)
  • Loading branch information
softwaresale committed Jul 30, 2024
1 parent 1ddb01b commit 2c83b9f
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/main/java/dk/brics/automaton/RegExp.java
Original file line number Diff line number Diff line change
Expand Up @@ -722,10 +722,19 @@ private boolean check(int flag) {

final RegExp parseUnionExp() throws IllegalArgumentException {
// check for start anchor, discard if necessary
if (peek("^")) {
next();
}

RegExp e = parseInterExp();
if (match('|'))
e = makeUnion(e, parseUnionExp());

// check for ending anchor, discard if necessary
if (peek("$")) {
next();
}

return e;
}

Expand Down Expand Up @@ -854,6 +863,19 @@ else if (match('"')) {
} else if (match('(')) {
if (match(')'))
return makeString("");
else if (peek("?")) {
// figure out if there is group stuff
char questionMark = next();
if (peek("=!<")) {
// =,! -> look ahead
// < -> look behind (<=, <!) or named capture group (<name>)
char operator = next();
throw new IllegalArgumentException(String.format("group construct %c%c is not supported", questionMark, operator));
} else if (peek(":")) {
// ?: -> non-capture group
next();
}
}
RegExp e = parseUnionExp();
if (!match(')'))
throw new IllegalArgumentException("expected ')' at position " + pos);
Expand Down
28 changes: 28 additions & 0 deletions src/test/java/dk/brics/automaton/RegExpTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,32 @@ public void throwException_when_singleBoundIsTooLarge() {
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("bound 1000 is too large to be compiled (must be <= 100)");
}

@Test
public void failToParse_lookAheadAssertion() {
assertThatThrownBy(() -> new RegExp("(?![a-z]+)"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("group construct ?!");
}

@Test
public void failToParse_lookAheadAssertion2() {
assertThatThrownBy(() -> new RegExp("(?=[a-z]+)"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("group construct ?=");
}

@Test
public void failToParse_lookBehindAssertion() {
assertThatThrownBy(() -> new RegExp("(?<![a-z]+)"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("group construct ?<");
}

@Test
public void failToParse_lookBehindAssertion2() {
assertThatThrownBy(() -> new RegExp("(?<=[a-z]+)"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("group construct ?<");
}
}

0 comments on commit 2c83b9f

Please sign in to comment.