0

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

1 Answer 1

1

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+.

Sign up to request clarification or add additional context in comments.

4 Comments

This is only true if you assume valid input (and that the posted in the only acceptable format, which seems like a decent assumption). This accepts 23325:24.
I am carrying over OP's own assumptions since I don't want to entertain too much guesswork.
What if i want to just accept max of two digits before and after :
@ItachiUchiha I added that to the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.