我有一个String,它可以包含以下两种时间格式中的任何一种:
我想使用正则表达式在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.
在这种情况下我应该使用什么正则表达式。我希望在新行中以两种时间格式分割文本。指导我。
答案 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"
答案 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));
}
<强>输出强>
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.