Match 24-hour formatted time with regex

I am trying to combine 24 hour time with regular expressions using egrep.

Here is my test.txt test file:

32:23:31 24:30:31 23:70:31 23:61:31 23:10:70 23:10:61 22:17:16 01:17:15 24:15:22 0:17:16 00:17:17 24:30:31 

Here is my regex:

 egrep '(2[0-3]|1[0-9]|0[0-9]|[^0-9][0-9]):([0-5][0-9]|[0-9]):([0-5][0-9]|[0-9])' test.txt 

Final matches:

 23:10:70 23:10:61 22:17:16 01:17:15 00:17:17 

Any idea why this corresponds to 23:10:70 and 23:10:61?

+4
source share
1 answer

In fact, this corresponds to 23:10:7 and 23:10:6 , but since you are not using the end of the line metacharacter $ at the end of the line, it will handle everything that follows.

 egrep '^(2[0-3]|1[0-9]|0[0-9]|[^0-9][0-9]):([0-5][0-9]|[0-9]):([0-5][0-9]|[0-9])$' test.txt 

In other words, you should only allow [0-9] at the end of the line if the matching digit is the last in the line, that is, if it is followed by $ .

Another option is to make the last digit be 0-padded if it is less than 10, i.e. instead of [0-9] use 0[0-9] . This will correspond to 23:10:07 , but not 23:10:7 . This is the same as what you already have for part of the watch.

+5
source

Source: https://habr.com/ru/post/1434373/


All Articles