import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static final String expressionPrefix = "${";
public static final String expressionSuffix = "}";
public static void main(String[] args) {
String context = "${a}我在${b}中${c}${d}${e}";
List<String> list = parse(context);
// ["a","b","c","d","e"]
System.out.println(JSONObject.toJSON(list));
context = replace(context, "a", "1");
context = replace(context, "b", "2");
// 1我在2中${c}${d}${e}
System.out.println(context);
}
/**
* 将内容中表达式替换为值
* @param context
* @param expressionValue 表达式中的值,不包含前缀和后缀
* @param value
* @return
*/
public static String replace(String context, String expressionValue, String value){
String oldValue = expressionPrefix + expressionValue + expressionSuffix;
// 转义正则表达式中的特殊字符
String escapedOldValue = oldValue.replaceAll("([\\[\\]{}()*+?.\\\\^$|])", "\\\\$1");
return context.replaceAll(escapedOldValue, value);
}
/**
* 解析所有表达式
* @param context
* @return
*/
public static List<String> parse(String context){
List<String> list = new ArrayList<>();
if(StringUtils.hasText(context)){
int root = 0;
while (true){
int start = context.indexOf(expressionPrefix, root);
if(start == -1){
break;
}
int end = context.indexOf(expressionSuffix, start + expressionPrefix.length());
if(end == -1){
break;
}else{
String tmp = context.substring(start + expressionPrefix.length(), end);
end = end + expressionSuffix.length();
list.add(tmp);
}
root = end;
}
}
return list;
}
}