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));
}
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.
See this code run at Ideone.com.
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.