Java regex to fetch HH:MM:SS from a string

280 views Asked by At

String time = "Thu Dec 22 01:12:22 UTC 2022";

How to fetch the HH:MM:SS (01:12:22) here using java regex . So the output should be 01:12:22 I am using the below code but its not working.

    System.out.println("Hello, World!");
    String time = "Thu Dec 22 01:12:22 UTC 2022";
    String pattren = "(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]";
    Pattern p = Pattern.compile(pattren);
    Matcher m = p.matcher(time);
    System.out.println("h");

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

There are 4 answers

0
Basil Bourque On BEST ANSWER

Regex is overkill here.

String#split

You could simply split the string by SPACE character, and take the fourth piece of text. Access the fourth piece with an index of three.

String timeText = input.split( " " )[ 3 ] ;

See this code run at Ideone.com.

01:12:22


Or, as commented, you could parse the entire string as a java.time object. Then extract the LocalTime. For this approach, see the Answer by Arvind Kumar Avinash, and the Answer by hc_dev.

0
Gregor Ophey On

To answer the question as stated.

As the first comment to the OPs question pointed out, there is a problem with the call to group. There is no group with index 1 in the pattern.

When running the code, java tells you the same:

~/src $ java test.java
Hello, World!
h
Exception in thread "main" 
java.lang.IndexOutOfBoundsException: No group 1
    at java.base/java.util.regex.Matcher.group(Matcher.java:646)
    at test.main(test.java:14) 

So with either no argument (as suggested by 4th bird), or 0 as argument (shown below), the code works as intended:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class test {
public static void main(String[] args) {
    System.out.println("Hello, World!");
    String time = "Thu Dec 22 01:12:22 UTC 20\22";                                              
    String pattren = "(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]";
    Pattern p = Pattern.compile(pattren);
    Matcher m = p.matcher(time);
    System.out.println("h");

    while (m.find()) {
        System.out.println(m.group(0));
    }
    return;
}
}
0
hc_dev On

Not as simple (KISS) like Basil suggested, but using Java's Time API elaborating on Ole's comment:

Steps using parser and temporal-query

Use java.time.format.DateTimeFormatter.parse() method:

String givenTime = "01:12:22";
String textWithTimeInside = "Thu Dec 22 "+ givenTime +" UTC 2022";

// create a formatter and parser for the given format
DateTimeFormatter timeParser = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz y", Locale.ROOT);

// parse the given text
var temporalParsed = timeParser.parse(textWithTimeInside);

// debug print the output of parsed Temporal (interface)
System.out.println(temporalParsed);

// extract time-part using a query
LocalTime localTime = temporalParsed.query(LocalTime::from);
System.out.println(localTime);

assert localTime.toString().equals(givenTime);

Prints:

{InstantSeconds=1671671542},ISO,UTC resolved to 2022-12-22T01:12:22
01:12:22

Run the demo on IDEone.

Shortcut

Using method parse(CharSequence text, TemporalQuery<T> query) directly:

LocalTime localTime = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz y", Locale.ROOT)
    .parse("Thu Dec 22 01:12:22 UTC 2022", LocalTime::from);

See also

Java Docs:

2
Arvind Kumar Avinash On

Regex is not the right tool for your requirement

As also suggested by anubhava and Basil Bourque, the best tool to use here is date-time API.

import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

class Main {
    public static void main(String[] args) {
        String strDateTime = "Thu Dec 22 01:12:22 UTC 2022";
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss VV uuuu", Locale.ENGLISH);
        ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, parser);
        LocalTime time = zdt.toLocalTime();
        System.out.println(time);

        // Or get the string representation
        String strTime = time.toString();
        System.out.println(strTime);
    }
}

Output:

01:12:22
01:12:22

An important piece of advice from Ole V.V.: If the time substring has zero seconds e.g. 01:12:00, the default implementation of LocalTime#toString removes the trailing :00. In that, you will need a formatter also to format the time.

class Main {
    public static void main(String[] args) {
        String strDateTime = "Thu Dec 22 01:12:00 UTC 2022";
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss VV uuuu", Locale.ENGLISH);
        ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, parser);
        LocalTime time = zdt.toLocalTime();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH);
        String strTime = time.format(formatter);
        System.out.println(strTime);
    }
}

Output:

01:12:00

Learn more about the modern Date-Time API from Trail: Date Time.