typedefcoder2
typedefcoder2

Reputation: 300

Extracting data from String using Java Regex

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

Upvotes: 0

Views: 5515

Answers (2)

Francisco Paulo
Francisco Paulo

Reputation: 6322

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!

Upvotes: 2

AlexR
AlexR

Reputation: 115328

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);
}

Upvotes: 5

Related Questions