业务需求:

根据字典值,计算出延后的日志,比如根据字典值,计算出这个api使用期限。

字典值如下:

 String[] exprs = new String[]{
            "period_90days","period_1year",
            "period_1day","period_2years",
            "period_free1year"
    };

规则,数字[day[s]|month(s)|year(s)] 即 数字日期单位

period_数字日期单位(eg.period_1year),表示正常授权

period_free数字日期单位(eg.period_free1year) 表示有时间限制的免费

数字随便你填写,他会根据表达式计算时间

import org.apache.commons.lang3.RegExUtils;
import org.junit.Test;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.function.Predicate;
import java.util.regex.Pattern;

public class TestRegex {

    Pattern pattern = Pattern.compile("period_[\\d+day[s]|\\d+year[s]]");
    Pattern freePattern = Pattern.compile("period_free[Trial|\\d+day[s]|\\d+year[s]]");
    String[] exprs = new String[]{
            "period_90days", "period_1year",
            "period_1day", "period_2years",
            "period_free1year"
    };

    Pattern noDigitPattern = Pattern.compile("[^0-9]+");


    @Test
    public void test() {
        Predicate<String> regex = pattern.asPredicate();

        Predicate<String> freeRegex = freePattern.asPredicate();


        int length = exprs.length;
        for (int i = 0; i < length; i++) {
            String expr = exprs[i];
            System.out.printf("%s   匹配结果    %b\n", expr, regex.test(expr));
        }


        System.out.println("===================================================");

        for (int i = 0; i < length; i++) {
            String expr = exprs[i];
            System.out.printf("%s   匹配结果    免费:%b\n", expr, freeRegex.test(expr));
        }

    }

    @Test
    public void testExtractDigit() {
        int length = exprs.length;

        String unit = null;
        for (int i = 0; i < length; i++) {
            String expr = exprs[i];

            LocalDateTime now = LocalDateTimeNow();

            String rawCnt = RegExUtils.removeAll(expr, noDigitPattern);
            if (StringUtils.isEmpty(rawCnt)) {
                return;
            }
            int offset = expr.indexOf(rawCnt);
            int base_addr = rawCnt.length() + offset;
            unit = expr.substring(base_addr, base_addr + 1);

            Integer cnt = Integer.valueOf(rawCnt);


            switch (unit) {
                case "y":
                    now = now.plusYears(cnt);
                    break;
                case "m":
                    now = now.plusMonths(cnt);
                    break;

                case "d":
                    now = now.plusDays(cnt);
                    break;

            }

            System.out.printf("%s   匹配结果    %s,日期标志:%s,计算后的时间;%s\n", expr, rawCnt, unit, now.format(DateTimeFormatter.ISO_DATE_TIME));
        }
    }
}
public LocalDateTime LocalDateTimeNow() {
    return LocalDateTime.now(ZoneId.of("+8"));
}

 

test方法:运行结果

 

 

testExtractDigit运行结果:

 

posted on 2020-01-03 15:33  你不知道的浪漫  阅读(769)  评论(0编辑  收藏  举报