views:

63

answers:

4

I have a string which has the below content

String msg="The variables &CHAG_EF and &CHAG_DNE_DTE can be embedded in the description "

String test1="22/10/2010 00:10:12"
String test2 = "25/10/2010 00:01:12"  

I need to search the string variable msg for the value "&CHAG_EF" and if it exists replace with the value of test1 and need to search the string variable msg for the value of "&CHAG_DNE_DTE" and if it exists replace with the value of test2.

How can i replace it.

+3  A: 

So simple!

String msg2 = msg.replace("&CHAG_EF", test1).replace("&CHAG_DNE_DTE", test2);

Nullstr1ng
Thanks a lot for the info
Arav
+1  A: 
 msg = msg.replace("&CHAG_EF", test1).replace("&CHAG_DNE_DTE", test2);
polygenelubricants
Thanks a lot for the info
Arav
+2  A: 

Strings in Java are immutable, so any of the "manipulation" methods return a new string rather than modifying the existing one. One nice thing about this is that you can chain operations in many cases, like this:

String result = msg.replace("&CHAG_EF", test1)
                   .replace("&CHAG_DNE_DTE", test2);
Jon Skeet
Thanks a lot for the info
Arav
+3  A: 

Firstly, Strings can't be modified in Java so you'll need to create new versions with the correct modified values. There are two ways to approach this problem:

  1. Dynamically hard-code all the replacements like other posters have suggested. This isn't scalable with large strings or a large number of replacements; or

  2. You loop through the String looking for potential variables. If they're in your replacement Map then replace them. This is very similar to How to create dynamic Template String.

The code for (2) looks something like this:

public static String replaceAll(String text, Map<String, String> params) {
  Pattern p = Pattern.compile("&(\\w+)");
  Matcher m = p.matcher(text);
  boolean result = m.find();
  if (result) {
    StringBuffer sb = new StringBuffer();
    do {
      String replacement = params.get(m.group(1));
      if (replacement == null) {
        replacement = m.group();
      }
      m.appendReplacement(sb, replacement);
      result = m.find();
    } while (result);
    m.appendTail(sb);
    return sb.toString();
  }
  return text;
}
cletus
Thanks a lot for the info
Arav