从java中的字符串中提取日期

时间:2018-02-05 19:31:20

标签: java string date string-matching

我有一个字符串如下:

String str = "skip=anthing&id='234234432234' and (timestamp le 2017-01-17T05:05:55:358Z and timestamp ge 2017-01-17T08:05:55:358Z)&format=json";

我想从字符串中提取日期部分,将其放在单引号内,并将其替换回原始字符串。

结果字符串应为

String str = "skip=anything&id='234234432234' and (timestamp le '2017-01-17T05:05:55:358Z' and timestamp ge '2017-01-17T08:05:55:358Z')&format=json"

1 个答案:

答案 0 :(得分:2)

您可以使用以下正则表达式

String input = "skip=anthing&id='234234432234' and (timestamp le 2017-01-17T05:05:55:358Z and timestamp ge 2017-01-17T08:05:55:358Z)&format=json";
String output = input.replaceAll("(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}:\\d{3}Z)", "'$1'");
System.out.println(output); // skip=anthing&id='234234432234' and (timestamp le '2017-01-17T05:05:55:358Z' and timestamp ge '2017-01-17T08:05:55:358Z')&format=json