Reputation: 1253
I have a String which could contain any of the below two time formats:
I want to split this string in java using regex.
example:
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."
expected output using split
using regex
should be:
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.
what regex should I use in this case. I want the spliting of text in both time formats in new line. guide me.
Upvotes: 0
Views: 164
Reputation: 424993
This regex splits the input as required:
(?=\(\d\d?:\d\d:\d\d [AP]M\)|\d\d?:\d\d [AP]M [^)])
See live regex demo.
Some test code:
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);
}
Output:
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.
Upvotes: 0
Reputation: 785058
You can use it like this in 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));
}
Output
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.
Upvotes: 0
Reputation: 43169
You could come up with something like:
(?<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"
See a demo on regex101.
Upvotes: 1