You can use the regex, .*?(\d{1,2}:\d{1,2}(?:\:\d{1,2}(?:\.\d{1,9})?)?).*
to match the whole string and replace it with the pattern matched by group#1.
Description of the regex:
.*?
: Matches (lazily) any character any number of times
(
: Start of capturing group#1
\d{1,2}:\d{1,2}
: One to two digits followed by one to two digits
(?:
: Start of the optional non-capturing group
\:\d{1,2}
: :
followed by one to two digits (for seconds)
(?:
: Start of the optional non-capturing group
\.\d{1,9}
: .
followed by one to nine digits (for nano seconds)
)?
: Close of optional non-capturing group
)?
: Close of optional non-capturing group
)
: Close of capturing group#1
.*
: Matches any character any number of times
Demo:
public class Main {
public static void main(String[] args) {
// Test strings
String[] wholeStringArr = { "The time is 7:00.", "The time is 7:00:05.", "The time is 7:00:05.1.",
"The time is 7:00:05.123.", "The time is 7:00:05.123456789." };
for (String wholeString : wholeStringArr) {
String timeOnlyString = wholeString.replaceAll(".*?(\\d{1,2}:\\d{1,2}(?:\\:\\d{1,2}(?:\\.\\d{1,9})?)?).*",
"$1");
System.out.println(timeOnlyString);
}
}
}
Output:
7:00
7:00:05
7:00:05.1
7:00:05.123
7:00:05.123456789
ONLINE DEMO
java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time
, the modern Date-Time API:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String wholeString = "The time is 7:00.";
String timeOnlyString = wholeString.replaceAll(".*?(\\d{1,2}:\\d{1,2}(?:\\:\\d{1,2}(?:\\.\\d{1,9})?)?).*",
"$1");
DateTimeFormatter dtf = DateTimeFormatter
.ofPattern("H:m[:s[.[SSSSSSSSS][SSSSSSSS][SSSSSSS][SSSSSS][SSSSS][SSSS][SSS][SS][S]", Locale.ENGLISH);
LocalTime time = LocalTime.parse(timeOnlyString, dtf);
System.out.println(time);
}
}
Output:
07:00
ONLINE DEMO
Notice the optional patterns in the square brackets.
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.