Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting placeholders from string [duplicate]

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?

like image 472
Etienne Poulin Avatar asked Apr 20 '26 09:04

Etienne Poulin


1 Answers

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

like image 141
Tim Biegeleisen Avatar answered Apr 22 '26 22:04

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!