Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java API for composing regular expressions

Tags:

java

regex

I am writing an application that needs to define and compile patterns at runtime. Using the Java Pattern API, I need to pass a string and get a pattern. Something like this:

Pattern.compile("ab*|c*");

The problem is that my patterns are modular and I would like to compose them using alternative, kleene star, etc, for example:

Char a = new Char('a');
Char b = new Char('b');
Char c = new Char('c');
Regex r = new Regex(new Alt(new Seq(a, new KleeneStar(b)), new KleeneStar(c)));
Pattern.compile(r);

I haven't found an API in JDK to allow me such a thing. I assume that the underlying implementation of pattern should have such an API. Does any one know how I can get such an API from the standard Java, or are there third party libraries for that?

In the end, I think I can create such an API myself with some recursive visitors to printout the string, but would be nice if it already exits.

like image 659
Wickoo Avatar asked Dec 23 '14 01:12

Wickoo


1 Answers

Try http://itsallbinary.com/project-simply-regex/

https://github.com/itsallbinary/simply-regex

Code examples:

String builtRegex = SimpleRegex.regex().startingWith().exactString("abc")
                                       .then().oneOfTheCharacters('d', 'e', 'f')
                                       .build();

SimpleRegex.regex().anywhereInText().oneOrMoreOf('a').build();

String builtRegex = SimpleRegex.regex().anywhereInText().oneOrMoreOf(groupHaving().exactString("abc").then().anyDigitChar().build())
                       .build()
like image 179
Ravi K Avatar answered Oct 17 '22 15:10

Ravi K