java 正则匹配json中占位符
使用场景
对于一些框架研发的时候,一些json配置文件我们可以使用占位符语法,然后可通过-Dkey=value传递到系统参数中,最后正则替换掉
代码
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.23</version>
</dependency>
<dependency>
<!--一些方便的工具类-->
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
package com.test;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
private static final String username = "张三";
private static final String passwrod = "game123(*&";
private static final Pattern VARIABLE_PATTERN = Pattern.compile("(\\$)\\{?(\\w+)\\}?");
public static void main(String[] args) throws IOException {
System.setProperty("username", username);
System.setProperty("password", passwrod);
String jsonString = IOUtils.toString(new FileInputStream("C:\\Users\\penggan\\Desktop\\novel\\Flink15\\src\\main\\resources\\core.json"), StandardCharsets.UTF_8);
String formatString = replaceVariable(jsonString);
System.out.println(formatString);
}
public static String replaceVariable(final String param) {
// 获取系统属性值-Dkey=value以填充${key}
Map<String, String> mapping = new HashMap<String, String>();
Matcher matcher = VARIABLE_PATTERN.matcher(param);
while (matcher.find()) {
String variable = matcher.group(2);
String value = System.getProperty(variable);
if (StringUtils.isBlank(value)) {
value = matcher.group();
}
mapping.put(matcher.group(), value);
}
String retString = param;
for (final String key : mapping.keySet()) {
retString = retString.replace(key, mapping.get(key));
}
return retString;
}
}