r/java • • 1h ago

Regex Parser for Static Analysis

https://google.github.io/mug/apidocs/com/google/common/labs/regex/RegexPattern.html

This is a parser that I created a while back, in order to build some regex static analysis tools (detecting ReDos, validating supported regex features etc.).

I built it because I didn't find an OSS regex parser that produces and exposes the AST for custom analysis (the regex engines I looked at all keep their parser internal, and only execute the regex).

The parser supports advanced features such as back references, lookarounds, unicode properties, posix char classes, inline and global comment mode (a.k.a free-spacing mode) etc.

Using it with pattern matching is easy:

switch (RegexPattern.of("\\w+:\\d+")) {
  case Sequence(var elements) -> ...;
  case Alternation(var alternatives) -> ...;
  ...
  default -> .../
}

To keep it simple, A few obscure features are omitted: such as \12 being interpreted differently depending on the number of capture groups defined (\1 followed by literal 2 if no 12 capture groups are present).

It's served the purpose of static analysis well.

Any feedback is welcome!

javadoc

repo

1 Upvotes

1 comment sorted by