2

Normally, people would use regexes to parse something else into an AST. What I'm looking for is a tool that I can use to parse the regex itself into an AST, which I can then manipulate symbolically. Let's say I have a regex like

(c(o)w)/(.*?)/omg

I want to be able to ask questions like

  • How many capturing groups are there?
  • Are there are nested groups?
  • Is the character ., 10th character in the regex, at the start of a capturing group?

And be able to manipulate the regex in some meaningful way, e.g:

  • Get the names of all named groups
  • Replace all named groups with un-named groups
  • Flatten any nested groups into their outer-most enclosing group

before serializing it back into a string.

I've poked around java.util.regex.Pattern, but it's internals are all private, so I don't have access to them. Are there any third party libraries which I can use to do this?

4
  • No, you should NEVER use a regexp to "parse" anything but the simplest regular grammars. They are called "regular expressions" for a reason.
    – SK-logic
    Feb 4, 2013 at 8:39
  • 1
    Nobody asked for a regexp to "parse" something. What are you talking about?
    – Li Haoyi
    Feb 4, 2013 at 10:26
  • I see, I did not read your question thoroughly. You want to parse regexps, not parse with regexps. Unlikely you'll find a ready to use library, but it should be trivial to implement your own.
    – SK-logic
    Feb 4, 2013 at 10:33
  • Yeah, I've come to that conclusion myself. I don't think it'll be trivial to do it on my own, but it looks like that's the way forward...
    – Li Haoyi
    Feb 4, 2013 at 14:39

2 Answers 2

4

I would use ANTLR to create a lexer/parser for regular expressions. Depending on how much of regular expression syntax you want to use, this may be easy to fairly complex. Antlr comes with a nice graphical editor where you can test the grammar file you are creating. The resulting AST is very easy to manipulate in a standard Java program. If you are new to Antlr, I would highly recommend the Antlr book by Terence.

2
  • You could also mention about ANTLR plugin for Eclipse antlrv3ide.sourceforge.net. Very good recommendation (+1)
    – Tom
    Jan 21, 2013 at 23:37
  • I've considered using ANTLR; I'm using Scala, so I also have the parser-combinator library available. My first choice would be some already made library though (if it exists!), since I hope to avoid becoming an expert in the intricacies regex grammar to do basic manipulation.
    – Li Haoyi
    Jan 22, 2013 at 0:28
3

Have a look at my ANTLR based PCRE parser: https://github.com/bkiers/PCREParser

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.