0

I have a string " 11:45 AM, 12:30 PM, 04:50 PM "

I wish to extract the first time from this string using java regex.

I have created a java regex like :

"\d*\S\d*\s(AM|PM)" for this.

However i can only match this pattern in Java rather than extract it. How can i extract the first token using the Regex i created

0

2 Answers 2

5

The capturing parentheses where missing. Here is the code sample that should help you.

Pattern p = Pattern.compile("(\d*):(\d*)\s(AM|PM)");
Matcher m = p.matcher(str);
if (m.find()) {
    String hours = m.group(1);
    String minutes = m.group(2);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Rewritten as : Pattern p= Pattern.compile("(\\d*):(\\d*)\\s(AM|PM)"); Matcher m = p.matcher(ShowTime[i]); if(m.find()) { String hours = m.group(1); String minutes = m.group(2); String timeFormat = m.group(3); String finalTime= hours+":"+minutes+" "+timeFormat; }
2

If you only want to extract the first time, you can use the parse method of SimpleDateFormat directly, like this:

    String testString = " 11:45 AM, 12:30 PM, 04:50 PM ";

    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
    Date parsedDate = sdf.parse(testString);

    System.out.println(parsedDate);

From the api, the partse method: "Parses text from the beginning of the given string to produce a date", so it will ignore the other two dates.

Regarding the pattern:

hh --> hours in am/pm (1-12)
mm --> minutes
aa --> AM/PM marker

Hope this helps!

2 Comments

Sorry could not try your solution. Thanks for Helping
Don't worry about that, maybe you'll get to use it in the future :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.