ITomas
ITomas

Reputation: 839

Convert filter into regex

I've been looking out if there is any java converter library to translate simple filters for example *something* into a regular expression like (.*)something(.*). The use case would be to allow end users to create regular expressions without knowing the whole regex syntax. Does anyone know if there is any work done or has anyone an idea how to accomplish it.

Upvotes: 1

Views: 521

Answers (2)

Riddhish.Chaudhari
Riddhish.Chaudhari

Reputation: 853

Follow this approach to replace all character.

you need:

jakarta-regexp-1.5.jar

standerd way to implement using build.properties or web.xml

<replaceregexp file="${src}/build.properties"
                         match="OldProperty=*"
                         replace="NewProperty=(.*)"
                         byline="true"/>

replaces occurrences of the property name "OldProperty" with "NewProperty" in a properties file, preserving the existing value, in the file ${src}/build.properties

see http://www.jajakarta.org/ant/ant-1.6.1/docs/en/manual/OptionalTasks/replaceregexp.html for more

Upvotes: 0

user
user

Reputation: 6947

KISS. Keep It Simple, Stupid.

Assuming you want * for zero or more characters, and ? for a single character (same as file name globbing on most OSes), you could just use something like this (typed in browser, so not tested, but you get the idea...)

String filterToRegexExpression(String filter) {
    String regexExpression = filter
        .replace('?', '.')
        .replace("*", "(.*)");
    return "^" + regexExpression + "$"; // anchor or not at either end, as desired
}

Then just create a regex instance and use this conversion function to convert the user-supplied filter string into a regular expression.

The above doesn't handle other regex-special characters very nicely, but I think you can do that by simply escaping anything non-alphanumeric. I'm leaving that as an exercise for the reader, though.

I doubt there are ready-made libraries for this, since that would require defining a universally acceptable but somehow easier regular expression syntax - while the application's needs (and expectations on the user's knowledge) tends to vary quite a bit. At that point, you can almost as well just ask them to input a regular expression, for which there are plenty of examples available.

Upvotes: 2

Related Questions