String replacement in java, similar to a velocity template

前端 未结 8 1313
小鲜肉
小鲜肉 2020-11-28 04:59

Is there any String replacement mechanism in Java, where I can pass objects with a text, and it replaces the string as it occurs.
For example, the text is :

相关标签:
8条回答
  • 2020-11-28 05:13

    I use GroovyShell in java to parse template with Groovy GString:

    Binding binding = new Binding();
    GroovyShell gs = new GroovyShell(binding);
    // this JSONObject can also be replaced by any Java Object
    JSONObject obj = new JSONObject();
    obj.put("key", "value");
    binding.setProperty("obj", obj)
    String str = "${obj.key}";
    String exp = String.format("\"%s\".toString()", str);
    String res = (String) gs.evaluate(exp);
    // value
    System.out.println(str);
    
    0 讨论(0)
  • 2020-11-28 05:15

    Here's an outline of how you could go about doing this. It should be relatively straightforward to implement it as actual code.

    1. Create a map of all the objects that will be referenced in the template.
    2. Use a regular expression to find variable references in the template and replace them with their values (see step 3). The Matcher class will come in handy for find-and-replace.
    3. Split the variable name at the dot. user.name would become user and name. Look up user in your map to get the object and use reflection to obtain the value of name from the object. Assuming your objects have standard getters, you will look for a method getName and invoke it.
    0 讨论(0)
  • 2020-11-28 05:25

    Use StringSubstitutor from Apache Commons Text.

    https://commons.apache.org/proper/commons-text/

    It will do it for you (and its open source...)

     Map<String, String> valuesMap = new HashMap<String, String>();
     valuesMap.put("animal", "quick brown fox");
     valuesMap.put("target", "lazy dog");
     String templateString = "The ${animal} jumped over the ${target}.";
     StringSubstitutor sub = new StringSubstitutor(valuesMap);
     String resolvedString = sub.replace(templateString);
    
    0 讨论(0)
  • 2020-11-28 05:28

    There are a couple of Expression Language implementations out there that does this for you, could be preferable to using your own implementation as or if your requirments grow, see for example JUEL and MVEL

    I like and have successfully used MVEL in at least one project.

    Also see the Stackflow post JSTL/JSP EL (Expression Language) in a non JSP (standalone) context

    0 讨论(0)
  • 2020-11-28 05:29

    Take a look at the java.text.MessageFormat class, MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

    Object[] params = new Object[]{"hello", "!"};
    String msg = MessageFormat.format("{0} world {1}", params);
    
    0 讨论(0)
  • 2020-11-28 05:31

    There is nothing out of the box that is comparable to velocity since velocity was written to solve exactly that problem. The closest thing you can try is looking into the Formatter

    http://cupi2.uniandes.edu.co/site/images/recursos/javadoc/j2se/1.5.0/docs/api/java/util/Formatter.html

    However the formatter as far as I know was created to provide C like formatting options in Java so it may not scratch exactly your itch but you are welcome to try :).

    0 讨论(0)
提交回复
热议问题