Frank Roth
Frank Roth

Reputation: 6339

Parsing text with variables like %NAME% in it

I have the following example text:

Peter Miller - Product Management ### 20000

Now I want to let my users define an easy matching pattern with the help of the percent characters, like:

%NAME% - %JOB% ### %AMOUNT%

The order of the variables and the characters between them can change! Does anybody know an existing ready to use implementation for this matching problem? I think RegExp is the wrong approach for this.

Upvotes: 2

Views: 60

Answers (1)

Florent Bayle
Florent Bayle

Reputation: 11890

I think that you can create a regexp from your pattern, and match it against the text.

Here is a quick example:

public static Map<String, String> match(final String pattern, final String text)  {
    final StringBuilder regexp = new StringBuilder("^");

    final List<String> varNames = new LinkedList<String>();
    int i=0;
    for (final String subPart : pattern.split("%", -1)) {
        if (i++%2!=0) {
            regexp.append("(.*)");
            varNames.add(subPart);
        } else {
            regexp.append(Pattern.quote(subPart));
        }
    }
    regexp.append("$");

    final Pattern p = Pattern.compile(regexp.toString());
    final Matcher m = p.matcher(text);


    final Map<String, String> matched = new HashMap<String, String>();
    if (m.matches()) {
        int j=1;
        for (final String varName : varNames) {
            matched.put(varName, m.group(j++));
        }
    }

    return matched;
}

You can call it like that:

public static void main(String[] args)  {
    final String pattern = "%NAME% - %JOB% ### %AMOUNT%";
    final String text = "Peter Miller - Product Management ### 20000";

    for (final Entry<String, String> e : match(pattern, text).entrySet()) {
        System.out.println(e.getKey()+"\t"+e.getValue());
    }
}

And the output is:

NAME    Peter Miller
JOB Product Management
AMOUNT  20000

Upvotes: 3

Related Questions