package com.fl.test;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.compile;
/**
* @author: fengli.fl
* @date: Created in 2020/11/18 14:23
* @description:
*/
public class TestStatement {
public static void main(String[] args) {
String value = "${fieldId-001}/#{function-001}(${fieldId-002},#{function-002})";
Map<String, String> map = new HashMap<>(2);
map.put("${fieldId-001}", "bps");
map.put("${fieldId-002}", "dps");
// 正则匹配 ${xx}
final Pattern pattern = compile("\\$\\{.*?\\}");
// 占位符可能匹配的次数
int count = value.split("\\$\\{").length - 1;
for (int i = 0; i < count; i++) {
Matcher matcher = pattern.matcher(value);
boolean flag = matcher.find();
if (!flag) {
break;
}
String key = matcher.group(0);
if (map.containsKey(key)) {
value = value.replace(key, map.get(key));
}
}
String func=value;
Map<String, String> functionMap = new HashMap<>(2);
functionMap.put("#{function-001}", "avg");
functionMap.put("#{function-002}", "sum");
// 正则匹配 ${xx}
final Pattern pattern1 = compile("\\#\\{.*?\\}");
// 占位符可能匹配的次数
int count1 = func.split("\\#\\{").length - 1;
for (int i = 0; i < count1; i++) {
Matcher matcher = pattern1.matcher(func);
boolean flag = matcher.find();
if (!flag) {
break;
}
String key = matcher.group(0);
if (functionMap.containsKey(key)) {
func = func.replace(key, functionMap.get(key));
}
}
System.out.println(func);
}
}
字符串${id}/#{functionId}的正则替换
最新推荐文章于 2024-05-04 13:00:00 发布