我想根据用户定义的表达式计算时间偏移量(天数)。该表达式将支持以下关键字:
+
- >增量-
- >减少D
- >天W
- >周M
- >月WD
- >工作日(非商业日历的假期)示例:
+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
答案 0 :(得分:1)
我会去
(([+-])(\d+)(WD|[DWM]))
[+ - ]:+或 - symbol
\ d +:至少一位数
WD:WD
| :或
[DWM]:D或W或M
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));
}