jeudi 13 avril 2017

Matcher, find and replace placeholders with values

I have an input String which is something like a query with placeholders, like this

#input String queryText, test, test2
//queryText is something like " SELECT stuff FROM stufftable WHERE oid_2 = $$test$$ || oid_2 = $$test2$$

Now my task is to replace those placeholders with the content of the inputs, the input variables have the same name of the placeholders, so variable test should replace placeholder $$test$$ and variable test2 should replace placeholder $$test2$$

Here's what I've written down as a test

    final List<String> list = new LinkedList<String>();
    Pattern pattern = Pattern.compile(/\$\$(.*?)\$\$/)
    Matcher matcher = pattern.matcher(queryText)
    log.debug(pattern)

    while (matcher.find()) {
        list.add(matcher.group(1));
        String text = matcher.group(1)
    log.debug(list)
    log.debug(text)
    }

And the output I have from the logs is the following:

\$\$(.*?)\$\$
[test]
test
[test, test2]
test2

So the placeholders are found correctly in groups, the part i miss is how to replace the values into them. I've tried .replaceFirst but it loops in the while, I've tried .replaceAll but it replaces all the placeholders at the first time so the others are not even found.

I hope it's clear, it's hard to explain. I'm here for any explanation.

Aucun commentaire:

Enregistrer un commentaire