0

I got a string test "{\"userName\": \"<userName>\",\"firstName\": \"<firstName>\",\"lastName\": \"<lastName>\"}". what I want is that I want to replace things in angular brackets with dynamic values. Sample code:

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String toBeReplaced0 = "alpha";
        String toBeReplaced1 = "beta";
        String toBeReplaced2 = "gama";

        String test = "{\"userName\": \"<userName>\",\"firstName\": \"<firstName>\",\"lastName\": \"<lastName>\"}";

    }

}

Now in this code I want to replace <userName> with alpha, <firstName> with beta, <lastName> with gama at once without making multiple string objects. This is not a homework question. test string can have more angular elements in it to be filled with dynamic values. How can I do this with replace method or any thing else..

3
  • Why do you want to avoid multiple String objects? The JVM is very good at handling them efficiently. Commented Nov 6, 2017 at 10:47
  • to avoid multiple string objects in pool. memory critical application. Commented Nov 6, 2017 at 10:48
  • 1
    Then you're using the wrong language. Commented Nov 6, 2017 at 10:48

3 Answers 3

1

Matcher.appendReplacement could be an option. Example:

public static void main(String[] args){
    String toBeReplaced0 = "alpha";
    String toBeReplaced1 = "beta";
    String toBeReplaced2 = "gama";
    String test = "{\"userName\": \"<userName>\",\"firstName\": \"<firstName>\",\"lastName\": \"<lastName>\"}";
    System.out.println(findAndReplace(test,toBeReplaced0,toBeReplaced1,toBeReplaced2));        
}
public static String findAndReplace(String original, String... replacments){
    Pattern p = Pattern.compile("<[^<]*>");
    Matcher m1 = p.matcher(original);
    // count the matches
    int count = 0;
    while (m1.find()){
        count++; 
    }
    // if matches count equals replacement params length replace in the given order
    if(count == replacments.length){
        Matcher m = p.matcher(original);
        StringBuffer sb = new StringBuffer();
        int i = 0;
        while (m.find()) {
            m.appendReplacement(sb, replacments[i]);
            i++;
        }
        m.appendTail(sb);            
        return sb.toString();
    }
    //else return original
    return original;
}
Sign up to request clarification or add additional context in comments.

Comments

1

If that's JSON, I'd prefer to use a JSON library to dynamically construct the resultant string and mitigate any possible syntactic errors.

If you really want to use String.replaceAll() or similar, I wouldn't expect that to be a problem in the above limited scope. Simply chain together your calls (e.g. see this tutorial)

Note that strings are immutable, and as such you can't easily do this without creating new string objects. If that's really a concern, perhaps you need to modify an array of chars (but that will be a non-trivial task when substituting multiple strings of varying lengths differing from their placeholders).

Simply:

String result = orig.replace("<userName>", "replacement");

(not forgetting that strings are immutable and so you have to use the result returned from this call)

Comments

1

I would do that with the StringTemplate library. With your example works out of the box:

    <dependency>
        <groupId>org.antlr</groupId>
        <artifactId>ST4</artifactId>
        <version>4.0.8</version>
        <scope>compile</scope>
    </dependency>

    // Given
    final ST template = new ST("{\"userName\": \"<userName>\",\"firstName\": \"<firstName>\",\"lastName\": \"<lastName>\"}");
    template.add("userName", "alpha");
    template.add("firstName", "beta");
    template.add("lastName", "gamma");
    // When
    final String result = template.render();
    // Then
    Assert.assertEquals("{\"userName\": \"alpha\",\"firstName\": \"beta\",\"lastName\": \"gamma\"}", result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.