Which regexp would find my datetime format?

Viewed 42

I created a regexp for a date with time, formatted like this:

25.06.19 / 16:30

I created the following regexp:

^[0-9]{2}\.[0-9]{2}\.[0-9]{4}\s.\/\s.[0-9]{2}\:[0-9]{2}$

The result should deliver the above match, but it doesn't. Can you help me fix my regexp?

1 Answers

Your year can consist of two or four digits, use

regex='^[0-9]{2}\.[0-9]{2}\.[0-9]{2}([0-9]{2})?[[:space:]]*/[[:space:]]*[0-9]{2}:[0-9]{2}$'
#                                   ^^^^^^^^^^^

Bash demo:

s="25.06.19 / 16:30"
regex='^[0-9]{2}\.[0-9]{2}\.[0-9]{2}([0-9]{2})?[[:space:]]*/[[:space:]]*[0-9]{2}:[0-9]{2}$'
if [[ "$s" =~ $regex ]]; then
  echo "Matched!"
fi;

Note I also replaced \s with [[:space:]] that should have wider support in Bash, and / does not need escaping as there are no regex delimiters here, and / is not a special regex metacharacter. Besides, the dots in \s.\/\s. are suspicious, I understand you wanted to match any 0 or more whitespaces, so I replaced . with *.

Related