根据模板自动匹配目标字符串

好的,让我们模拟一下这段代码的运行,并打印出每一行的结果:

// 声明一个静态的正则表达式模式,用于匹配大括号中的内容
private static final Pattern pattern = Pattern.compile("\\{(.*?)\\}");

private static Matcher matcher;

// 字符串格式化替换方法
public String formatString(String sourceString, Map<String, Object> param) {
    // 检查源字符串和参数是否为空,如果其中任何一个为空,则直接返回源字符串
    if (StringUtils.isEmpty(sourceString) || CollectionUtils.isEmpty(param)) {
        return sourceString;
    }

    String targetString = sourceString; // 初始化目标字符串为源字符串的副本
    System.out.println("目标字符串初始化为:" + targetString);

    matcher = pattern.matcher(sourceString); // 使用正则表达式模式创建一个匹配器对象,来对源字符串进行匹配查找

    String key = null;
    String keyClone = null;
    Object value = null;

    while (matcher.find()) {
        try {
            key = matcher.group(); // 获取匹配项
            System.out.println("找到匹配项:" + key);
            
            keyClone = key.substring(1, key.length() - 1).trim(); // 去除大括号后将键进行克隆,并去除两边的空格
            System.out.println("克隆后的键:" + keyClone);
            
            value = param.get(keyClone); // 根据克隆后的键从参数映射中获取相应的值
            System.out.println("参数映射中对应的值:" + value);
            
            if (value != null) { // 如果找到非空值,则将目标字符串中的匹配项替换为对应值
                targetString = targetString.replace(key, value.toString());
                System.out.println("替换后的目标字符串:" + targetString);
            }
        } catch (Exception e) { // 如果在提取键或替换过程中发生异常,则抛出运行时异常
            throw new RuntimeException("String formatter failed", e);
        }
    }

    return targetString; // 返回最终的目标字符串
}

让我们假设有一段源字符串 sourceString 是 "Hello, {name}! Welcome to {place}.",并且参数映射 param{name=John, place=New York}

现在,我们来逐行执行代码并打印结果:

目标字符串初始化为:Hello, {name}! Welcome to {place}.
找到匹配项:{name}
克隆后的键:name
参数映射中对应的值:John
替换后的目标字符串:Hello, John! Welcome to {place}.
找到匹配项:{place}
克隆后的键:place
参数映射中对应的值:New York
替换后的目标字符串:Hello, John! Welcome to New York.

从输出结果可以看出,代码成功地将源字符串中的占位符 {name}{place} 分别替换为了对应的值 "John" 和 "New York",最终得到了替换后的目标字符串 "Hello, John! Welcome to New York."。

希望这个例子能够帮助您更好地理解代码的运行过程。如有其他问题,请随时提问。

posted @ 2023-07-14 15:49  天意啊  阅读(37)  评论(0)    收藏  举报