日偏移的正则表达式

时间:2015-03-23 15:01:21

标签: java regex quartz-scheduler

我想根据用户定义的表达式计算时间偏移量(天数)。该表达式将支持以下关键字:

  1. + - >增量
  2. - - >减少
  3. D - >天
  4. W - >周
  5. M - >月
  6. WD - >工作日(非商业日历的假期)
  7. 示例:

    +3D means adding 3 days to the offset
    -3D means reduce 3 day from the offset
    +34M+3D means adding 34 months and 3 days to the offset
    +3D+1WD  means adding 3 days and then add one extra working day.
    

    问题是我不知道如何编写正则表达式来处理字符串。有人能给我一些例子吗?

    这是我到目前为止尝试的,请注意第二个令牌不正确

    Pattern p = Pattern.compile("[+-]+([0-9]+)[WD|D|W|M]");
     Matcher m = p.matcher("+1D-2WD+3M");
    while(m.find()){
        System.out.println(m.group(0));
    }
    

    结果:

    +1D
    -2W
    +3M
    

1 个答案:

答案 0 :(得分:1)

我会去

(([+-])(\d+)(WD|[DWM]))

[+ - ]:+或 - symbol

\ d +:至少一位数

WD:WD

| :或

[DWM]:D或W或M

Working example

Pattern p = Pattern.compile("(([+-])(\\d+)(WD|[DWM]))");
        Matcher m = p.matcher("+1D-2WD+3M");
        while(m.find()){
            System.out.println(m.group(1));
            // Splitted argument
            System.out.println("Operator : " +  m.group(2));
            System.out.println("Number : " +  m.group(3));
            System.out.println("Period : " +  m.group(4));

        }