All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zyy.common.util.RegUtil Maven / Gradle / Ivy

package com.zyy.common.util;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class RegUtil {
    /**
     * 根据正则表达式获取文本中的变量名列表
     *
     * @param pattern 正则表达式
     * @param content 内容
     * @return 结果
     */
    public static List getParams(String pattern, String content) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(content);

        List result = new ArrayList<>();
        while (m.find()) {
            result.add(m.group(1).trim());
        }
        return result;
    }

    /**
     * 根据正则表达式将文本中的变量使用实际的数据替换成无变量的文本
     *
     * @param pattern 正则
     * @param content 内容
     * @param obj     数据
     * @return 结果串
     */
    public static String parse(String pattern, String content, Object obj, TokenModel tokenModel) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(content);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String key = m.group(1);
            try {
                String[] ps = key.trim().split("\\.");
                Field field;
                Object value = null;
                if (ps.length == 2 && "request".equals(ps[0])) {
                    if (tokenModel != null) {
                        Field f = ReflexUtil.getFiled(tokenModel, ps[1]);
                        if (f != null) {
                            f.setAccessible(true);
                            value = f.get(tokenModel);
                        }
                    }
                } else {
                    value = obj;
                    for (String s : ps) {
                        if (value == null) break;
                        field = ReflexUtil.getFiled(value, s);
                        if (field == null) {
                            value = null;
                            break;
                        }
                        field.setAccessible(true);
                        value = field.get(value);
                    }
                }
                m.appendReplacement(sb, value == null ? "" : value.toString());
            } catch (IllegalAccessException e) {
                log.info("", e);
            }
        }
        m.appendTail(sb);
        return sb.toString();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy