Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace field value(s) in a String

Tags:

java

guava

Using Google Guava is there String utility to easily replace string field inside like this:

String query = mydb..sp_mySP ${userId}, ${groupId}, ${someOtherField}

Where I can do something like this:

StringUtil.setString(query)
   .setField("userId", "123")
   .setField("groupId", "456")
   .setField("someOtherField", "12-12-12");

Then the resulting String would be:

mydb..sp_mySP 123, 456, 12-12-12

Of course, setting the String field patter like ${<field>} before the operation...

Anyway, this is my approach:

public class StringUtil {
    public class FieldModifier {
        private String s;
        public FieldModifier(String s){
            this.s = s;
        }
        public FieldModifier setField(String fieldName, Object fieldValue){
            String value = String.valueOf(fieldValue);
            s = modifyField(s, fieldName, value);
            return new FieldModifier(s); 
        }
        public String get() {
                return s;
        }
        private String modifyField(String s, String fieldName, String fieldValue){
            String modified = "";
            return modified;
        }
    }
    public FieldModifier parse(String s){
        FieldModifier fm = new FieldModifier(s);
        return fm; 
    }
}

So in this case, I just need to put the actual code in the modifyField function that will modify the string in a straightforward way. Also if there's a way so the parse function be static so I can just do StringUtil.parse(...) without doing new StringUtil().parse(...) which really doesn't look good.

like image 990
quarks Avatar asked Jul 19 '26 09:07

quarks


2 Answers

There's no such thing in Guava. You can have a look at SpEL (Spring Expression Language) which can do string templating, or other templating frameworks such as Velocity or Freemarker.

like image 51
Frank Pavageau Avatar answered Jul 20 '26 22:07

Frank Pavageau


Yes, String.format().

String s = "Hey %s! Cool %s, right?";
System.out.println(String.format(s, "xybrek", "feature"));
like image 36
Björn Avatar answered Jul 20 '26 22:07

Björn