开发者

Replacing variable in String

开发者 https://www.devze.com 2022-12-22 16:42 出处:网络
I have a string which has the below content String msg = \"The variables &CHAG_EF and &CHAG_DNE_DTE can be embedded\"

I have a string which has the below content

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

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 string "&CHAG_EF" a开发者_JAVA百科nd if it exists replace with the value of test1 and also search the string variable msg for the string "&CHAG_DNE_DTE" and if it exists replace with the value of test2.

How can i replace them?


So simple!

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


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;
}


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);


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号