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
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);
}
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.