[SOLVED] Replace a String with specific list of strings in java

Issue

Here is the example,

public class Demo{

    public static void main (String args[]) {

        List<String> varList = Arrays.asList("VAR_TEMP", "VAR_TEMPA", "VAR_TEMPB");
        String operation = "var temp = VAR_TEMPB";

        for (String var : varList) {
            operation = (operation.contains(var))
                    ? operation.replace(var, "'HI'")
                            : operation;
        }

        System.out.println("Final operation : " + operation);
    }
}

I am trying to replace the Operation string with list of strings.

I am expecting the response for the above code is like,

Final operation : var temp = HI

But it is giving the response like below,

Final operation : var temp = ‘HI’B

While iterating the list of String it is taking the first matching("VAR_TEMP") instead of taking the exact match("VAR_TEMPB").
Can you please suggest the way to achieve this the expected response.

Solution

List is declared as
List<String> varList = Arrays.asList("VAR_TEMP", "VAR_TEMPA", "VAR_TEMPB");

Operation is String operation = "var temp = VAR_TEMPB";

The loop acts as following:

  1. Does operation (var temp = VAR_TEMPB) contains VAR_TEMP? Yes
  2. Now operation now is var temp = ‘HI’B
  3. Does operation (var temp = ‘HI’B) contains VAR_TEMPA? No. Operation is not changed
  4. Does operation (var temp = ‘HI’B) contains VAR_TEMPB? No. Operation is not changed

A simple solution should be the use of Regular Expression, when you express the exact matching pattern. For example:

class Scratch {
  public static void main(String[] args) {
    final List<Pattern> varList =
        Arrays.asList(
            Pattern.compile("(VAR_TEMP)$"),
            Pattern.compile("(VAR_TEMPA)$"),
            Pattern.compile("(VAR_TEMPB)$"));

    String operation = "var temp = VAR_TEMPB";

    Matcher tmp;
    for (Pattern item : varList) {
      tmp = item.matcher(operation);
      operation = tmp.find() ? operation.replace(tmp.group(), "'HI'") : operation;
    }

    System.out.println("Final operation : " + operation);
  }
}

Answered By – sigur

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *