ItachiUchiha
ItachiUchiha

Reputation: 36722

java regular Expression, fetching time out of a string

I am new to regex in java..

i have a string "2:05pm - 2:40 pm" i need to get "2:05pm" and "2:40 pm" out from the single string using regex

I am using the follow regex expression, but I am getting wrong somewhere, don't know where

public static void main(String args[])
{
    Pattern MY_PATTERN = Pattern.compile("(\\d+)[:](\\d+)(\\s*)((am?)|(pm?))");
    String s = "2:05pm - 2:40pm";
    Matcher m = MY_PATTERN.matcher(s);
    int i=1;
    while (m.find()) {
        System.out.println(m.group(i++));
    }
}

Upvotes: 0

Views: 353

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200148

Your usage of group is wrong: you must always use group(0), which refers to the entire current match.

Overall, your regex is much too complicated, this is enough:

"\\d+:\\d+\\s*(a|p)m?"

which works in case you want input such as 1:10 a and 1:10p accepted, but not 1:10. Otherwise you should use this:

"\\d+:\\d+\\s*(am|pm)?"

which will accept 1:10, 1:10 am, but not 1:10 a.

If you want to validate a maximum of two digits, then use \\d{1,2} where you now use \\d+.

Upvotes: 1

Related Questions