Extracting placeholders from string

Etienne Poulin :

I got 2 strings. One contains the "format" and placeholders, while the other contains the actual value for the placeholders.

For example:

String one: "<username> <password>"

String two: "myUser myPass"

String one: "<name>, <familyName>"

String two: "John, Smith"

I'm trying to assign the variable String username the value of the username placeholder in the second string, and the variable String password the value of the password placeholder in the second string.

I know about the String.replaceAll() method, but wouldn't that just replace the first string by the second?

Tim Biegeleisen :

One potentially viable way to approach this would be to maintain a map of tokens and their replacements. Then, you may iterate that map and apply the replacements to your text, something like this:

String text = "There is a user <username> who has a password <password>";
Map<String, String> tokens = new HashMap<>();
tokens.put("<username>", "myUser");
tokens.put("<password>", "myPass");

for (Map.Entry<String, String> entry : tokens.entrySet()) {
    text = text.replaceAll(entry.getKey(), entry.getValue());
}

System.out.println(text);

There is a user myUser who has a password myPass

Demo

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=96108&siteId=1