0

I have a below string value in my java class.

Nazar 1:46 PM Hello, I have few questions related to API Management 1:46 PM Sadhana has joined

I want to split it on the basis of time mentioned in it. It should show a output in such a way that whenever a time value comes, it creates a new line break. Like below:

Nazar 1:46 PM Hello, I have few questions related to API Management. 1:46 PM Sadhana has joined

How can I accomplish this.

JPG
  • 1,247
  • 5
  • 31
  • 64

5 Answers5

2

You can also use this regex.

(?=\b(((11|12|10|(0[1-9]{1})):)|[\d]:)[0-5][0-9](\s)?(?i)(am|pm))

Descritpion:

It should match hh:mm AM/PM and also h:mm AM/PM.

hh    -> hours 01-09 or 10,11,12 or 1-9
mm    -> minutes 00-59
AM/PM -> case insensitive

Usage:

 String text = "Nazar 11:46 PM Hello, I have few questions related to API Management 10:46 PM "
            + "Sadhana has joined 06:35 AM its early 6:50 PM and late";

    String texts[] = text.split("(?=\\b(((11|12|10|(0[1-9]{1})):)|[\\d]:)[0-5][0-9](\\s)?(?i)(am|pm))");  

    for(String s : texts){
        System.out.println(s);
    }

Output:

Nazar 
11:46 PM Hello, I have few questions related to API Management 
10:46 PM Sadhana has joined 
06:35 AM its early 
6:50 PM and late
Patrick
  • 12,336
  • 15
  • 73
  • 115
1

You can try something like this:

str.split("(?=\\d{1,2}:\\d{1,2} (AM|PM))");
Titus
  • 22,031
  • 1
  • 23
  • 33
1

You can use this regex to split:

String[] arr = str.split("(?=(?<!\\d:)\b\\d{1,2}:\\d{1,2}(?::\\d{1,2})? [AP]M\b)\\s*");

It is important to use word boundaries \b on either side of lookahead pattern:

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thank you, anubhava. Your code worked for me. But right now there is one more issue raised. The issue is that input string can contain two time formats at same time. i.e. 1:46 PM & (2:49:02 PM). How can I split that particular string that contain both of these time formats, in line wise. Your guidance needed. – JPG Jan 13 '16 at 07:08
0

This regex should create your desired output.

String s = "Nazar 1:46 PM Hello, I have few questions related to API Management 10:46 PM Sadhana has joined";
String s1[] = s.split("(\\s)(?=([01]?\\d:[0-6]?\\d\\s?([Aa]|[Pp])[Mm]))");
for (String s2 : s1) {
    System.out.println(s2);
}
SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
0

Java has a class called Matcher using which you can find the occurrences of a given pattern.

This question has suitable solution in the link : Get the index of a pattern in a string using regex

Community
  • 1
  • 1
Harish Kumar
  • 1
  • 1
  • 1