java正则表达式

1、包含{{ cart.total_price }},不包含 minus:

Pattern.compile("(\\{\\{\\s*cart.total_price\\s*\\|*(?!.*minus:)[^\\}\\}]*\\}\\})");

校验:
{{ cart.total_price}} 通过
{{ cart.total_price | money_without_trailing_zeros }} 通过
{{ cart.total_price | minus: threshold_in_cents | abs | money_without_trailing_zeros }} 不通过

2、正则表达式匹配 {key} ,并且替换 key 内容

public static final String CONTAINS = "(?<=\\{)(.*?)(?=\\})";

    /**
     * 解析消息模板
     *
     * @param template 模板字符串
     * @param datas    模板填充数据
     * @return 解析结果
     */
    public static String parseMessage(String template, Map<String, Object> datas) {

        Pattern pattern = Pattern.compile(CONTAINS);
        Matcher matcher = pattern.matcher(template);
        StringBuffer parseContent = new StringBuffer();
        String key = "";
        int start = 0;
        while (matcher.find()) {
            key = matcher.group().trim();
            parseContent.append(template.substring(start, matcher.start() - 1));
            parseContent.append(datas.get(key));
            start = matcher.end() + 1;
        }
        if (parseContent.equals("")) {
            parseContent.append(template);
        } else {
            parseContent.append(template.substring(start));
        }

        return parseContent.toString();
    }

    public static void main(String[] args) {
        String template = "亲爱的主人,{enterprise}企业发布了{task}任务,为了毛栗,冲鸭!";
        Map<String, Object> datas = new HashMap<>();
        datas.put("enterprise", "龙珠");
        datas.put("task", "天下第一武道会");
        String result = parseMessage(template, datas);
        System.out.println(result);
    }

3、从字符串中抽取数字

    private static final Pattern pattern_number = Pattern.compile("\\d+");

    /**
     * 抽取数字
     *
     * @param text 内容
     * @return 数字
     */
    public List<BigDecimal> extractNumber(String text) {

        Matcher matcher = pattern_number.matcher(text);
        List<BigDecimal> numberList = new ArrayList<>();
        while (matcher.find()) {
            numberList.add(new BigDecimal(matcher.group()));
        }
        if (CollectionUtil.isNotEmpty(numberList)) {
            return numberList;
        }
        return Collections.emptyList();
    }

使用说明

?<= 表示后面的内容是否等于
?<= 表示以后面的内容开头
?! 表示后面的内容是否不是这个
?<!= 表示后面的内容是否不以这个开头

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值