在java中使用正则表达式为时间格式拆分字符串

时间:2016-01-13 07:24:36

标签: java regex

我有一个String,它可以包含以下两种时间格式中的任何一种:

  • 1:46 PM
  • (2:49:02 PM)

我想使用正则表达式在java中拆分此字符串。

例如: String str="hello ram, you logged in at1:46 PM we welcome you. Hello ram you logged out at(2:49:02 PM) see you again."

使用split使用regex的预期输出应为:

hello ram, you logged in at

1:46 PM we welcome you. Hello ram you logged out at

(2:49:02 PM) see you again.

在这种情况下我应该使用什么正则表达式。我希望在新行中以两种时间格式分割文本。指导我。

3 个答案:

答案 0 :(得分:1)

你可以想出类似的东西:

(?<tsp>\d+(?::\d+)+)\s[AP]M
# Looks for a digit (minimum 1)
# followed by at least one (or multiple pairs) of ":" and another digit
# this pattern is captured in a named group called tsp
# ... which in turn is followed by a whitespace and "AM" or "PM"

查看demo on regex101

答案 1 :(得分:0)

您可以在Java中使用它:

Pattern p = Pattern.compile(
  "(?im)((?:^|\\(?\\d+(?::\\d+)+\\s+[AP]M\\)?).*?)(?=\\(?\\d+(?::\\d+)+\\s+[AP]M\\)?|$)");

Matcher m = p.matcher(input);

while (m.find() {
   System.out.println(m.group(1));
}

RegEx Demo

<强>输出

hello ram, you logged in at
1:46 PM we welcome you. Hello ram you logged out at
(2:49:02 PM) see you again.

答案 2 :(得分:0)

此正则表达式根据需要拆分输入:

(?=\(\d\d?:\d\d:\d\d [AP]M\)|\d\d?:\d\d [AP]M [^)])

请参阅live regex demo

一些测试代码:

public static void main (String[] args) {
    String str="hello ram, you logged in at1:46 PM we welcome you. Hello ram you logged out at(2:49:02 PM) see you again.";
    Arrays.stream(str.split("(?=\\(\\d\\d?:\\d\\d:\\d\\d [AP]M\\)|\\d\\d?:\\d\\d [AP]M [^)])")).forEach(System.out::println);
}

输出:

hello ram, you logged in at
1:46 PM we welcome you. Hello ram you logged out at
(2:49:02 PM) see you again.