Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you match military time? [duplicate]

Tags:

java

regex

I'm trying to create a valid Java regex for matching strings representing standard "military time":

String militaryTimeRegex = "^([01]\d|2[0-3]):?([0-5]\d)$";

This gives me a compiler error:

Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )

Where am I going wrong?!?

like image 708
IAmYourFaja Avatar asked Dec 13 '25 13:12

IAmYourFaja


2 Answers

Make sure you use double backslashes for escaping characters:

String militaryTimeRegex = "^([01]\\d|2[0-3]):?([0-5]\\d)$";

Single backslashes indicate the beginning of an escape sequence. You need to use \\ to get the character as it appears in the String.


To answer your comment, you are currently only matching 19:00. You need to account for the additional :00 at the end of the String in your pattern:

String militaryTimeRegex = "^([01]\\d|2[0-3]):?([0-5]\\d):?([0-5]\\d)$";
like image 173
Reimeus Avatar answered Dec 15 '25 08:12

Reimeus


In Java, you need to double-escape all the \ characters:

String militaryTimeRegex = "^([01]\\d|2[0-3]):([0-5]\\d):([0-5]\\d)$";

Why? because \ is the escape character for strings, and if you need a literal \ to appear somewhere inside a string, then you have to escape it, too: \\.

like image 31
Óscar López Avatar answered Dec 15 '25 09:12

Óscar López