3

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?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Welcome to the site. You should try something even if you think it wouldn't produce the expected result. This would help others understand what you are trying to do. Currently, the explanation is insufficiently clear to understand the specifics of what you are trying to do. – Sergey Kalinichenko Aug 09 '18 at 15:39
  • Use [replace](https://docs.oracle.com/javase/10/docs/api/java/lang/String.html#replace(java.lang.CharSequence,java.lang.CharSequence)), not replaceAll. Regular expressions are too heavyweight and unnecessarily complex for this kind of replacement. – VGR Aug 09 '18 at 15:39
  • 1
    Welcome to StackOverflow. Sorry, this is not how this site works. As explained in the [tour], this site is a repository of useful questions and their answers, ***not a help forum***. Please take the [tour], visit the [help] and especially read [ask] and [Why is “Can someone help me?” not an actual question?](http://meta.stackoverflow.com/q/284236/18157) to learn how to use this site effectively. – Jim Garrison Aug 09 '18 at 15:39
  • 1
    Hi, thanks for that. I'm not used to forums, or stackoverflow at all. I'll check theses links and try to get used to how this site works. – Etienne Poulin Aug 09 '18 at 15:42

3 Answers3

3

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

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

This solves an ordinary String::replaceAll method:

String one ="<username> <password>";
String two = "<name>, <familyName>";

String username = "myUser";
String password = "myPass";
String name = "John";
String familyName = "Smith";

// will result in "myUser myPass" without the quotation marks
String outputOne = one.replaceAll("<username>", username).replaceAll("<password>", password);

// will result in "John Smith" without the quotation marks
String outputTwo = two.replaceAll("<name>", name).replaceAll("<familyName>", familyName);
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
0

I would suggest to go ahead and use regex for this. First capture all keys keys from String 1 and create corresponding regex from which take values from String 2

Code to extract keys and corresponding values:

    String keyString = "<name>, <familyName>";
    int i  = 0;
    List<String> keys = new ArrayList<>();
    Pattern pattern = Pattern.compile("<(\\w+)>");
    Matcher matcher = pattern.matcher(keyString);
    StringBuilder sb = new StringBuilder("");
    while(matcher.find()) {
            String token = matcher.group(1);
        sb.append(keyString.substring(i, matcher.start()));
        sb.append("([\\w ]+)");
        keys.add(token);
        i = matcher.end();
    }

    Pattern valuePattern = Pattern.compile(sb.toString());
    Matcher valueMatcher = valuePattern.matcher("John, Smith");
    Map<String,String> keyValueMap = new HashMap<>();
    while(valueMatcher.find()) {
        int counter = 0;
        for(String key:keys) {
            keyValueMap.put(key, valueMatcher.group(++counter));
    }
}

Similary execute for all other key value pairs.

Final JShell Output:

jshell> keyValueMap
keyValueMap ==> {password=myPass, familyName=Smith, name=John, username=myUser}
Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39
  • 1
    Sounds good. Can you elaborate on this? For example, showing a full code example? – Zabuzard Aug 09 '18 at 15:41
  • As I understand the question, the OP wants to find e.g. a `` placeholder in the text, and then replace it with some known value. Your regex code is just finding placeholders, but I don't see any replacements happening. – Tim Biegeleisen Aug 09 '18 at 15:45
  • @TimBiegeleisen I think OP wants to create a key value pair, I shared an idea earlier, but now I have also updated with the code – Aman Chhabra Aug 09 '18 at 15:58
  • @Zabuza I have edited my answer and shared code snippet with output as well. Hope that helps you – Aman Chhabra Aug 09 '18 at 16:05
  • Why down vote ? – Aman Chhabra Aug 09 '18 at 16:10
  • 1
    The vote was from before the edit. So I guess it was because your answer did not fully solve the issue back then. It was only a hint or comment. Now it's way better, have my up-vote :) – Zabuzard Aug 09 '18 at 16:21