Replace field value(s) in a String
Posted
by
xybrek
on Stack Overflow
See other posts from Stack Overflow
or by xybrek
Published on 2012-09-13T09:04:32Z
Indexed on
2012/09/13
9:38 UTC
Read the original article
Hit count: 165
java
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);
}
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.
© Stack Overflow or respective owner